Upload image file name - incorrect

Upload image file name - incorrect

cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

I need some help. I have been successful in uploading images and they are being stored on to my server. But the trouble is when I look in my database the file name is incorrect. Not sure why that it is.

According to my database the incorrect file name is "editor-fileName". But according to my saving feature of this line of code...

->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'] . '/images/.../profile__ID__.__EXTN__' )

This gives the correct file name on my server. But storing it into the database with this line of code is incorrect...

->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'] . '/images/.../profile__ID__.__EXTN__' )
                                ->db( 'Table', 'ID', array(
                                    'Field' => $pathToImg . Upload::DB_FILE_NAME
                                ) )

But according to the documentation: https://editor.datatables.net/manual/php/upload#Database-information

It says that "Upload::DB_FILE_NAME File name (with extension)"

But it's not doing what I want it to. How do I tell it the File Name is what I saved it to? How do I do that?

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    'Field' => $pathToImg . Upload::DB_FILE_NAME

    That's not going to work I'm afraid. What happens there is that $pathToImg is concatenated with the static value Upload::DB_FILE_NAME (which happens to be editor-fileName) and that value is then written to the database. It won't just replace the Upload::DB_FILE_NAME value as it does an if ( Upload::DB_FILE_NAME === $input ) ....

    What you would need to do instead is use a little anonymous function:

    'Field' => function ( $upload ) use ( $pathToImg ) {
      return $pathToImg . $upload['name'];
    }
    

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    Thanks for the response. This is getting me on the right path I believe. But for whatever reason $upload doesn't have the info that I need. I did a var_dump on $upload and it told me this.

    object(DataTables\Database)#2 (2) {
      ["_db":"DataTables\Database":private]=>
      object(PDO)#3 (0) {
      }
      ["query_driver"]=>
      string(36) "DataTables\Database\DriverMysqlQuery"
    }
    

    Is there anything else you can recommend I can get the filename? All I want to store is the URL + filename, example, http://example.com/filename.jpg

    Thanks!

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Just in case I am posting my new code to be sure I have followed your advice correctly.

    Field::inst( 'Table.urlToImage' )
                                ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'] . '/images/.../profile__ID__.__EXTN__' )
                                    ->db( 'Table', 'ID', array(
                                        'urlToImage' => function ( $upload ) use ( $pathToImg ) {
                                            error_log("Upload: " . $upload["urlToImage"] . " Array Length: " . count($upload) . "\n", 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
                                          return $pathToImg;
                                        }
                                    ) )
    

    The error that I am receiving according to the Network Tab is "Cannot use object of type DataTables\Database as array"

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    Sorry - could you try:

    Field::inst( 'Table.urlToImage' )
                                ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'] . '/images/.../profile__ID__.__EXTN__' )
                                    ->db( 'Table', 'ID', array(
                                        'urlToImage' => function ( $db, $upload ) use ( $pathToImg ) {
                                            error_log("Upload: " . $upload["urlToImage"] . " Array Length: " . count($upload) . "\n", 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
                                          return $pathToImg;
                                        }
                                    ) )
    

    I missed a parameter!

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Allan,

    This is gotten me much closer to what I wanted. The missing parameter was a good catch. When I did a "var_dump" on $upload I was able to see the attributes about the file; file name, file type, size, etc.

    So thanks for that.

    However, with this new change it was not what I was expecting it to be. This is my fault on describing what I wanted. Please be patient with me and tell me if this is doable or not.

    Field::inst( 'Table.urlToImage' )
       ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'] . '/images/.../profile__ID__.__EXTN__' )
          ->db( 'Table', 'ID', array(
             'urlToImage' => function ( $upload ) use ( $pathToImg ) {
                return $pathToImg . 'profile__ID__.__EXTN__';
             }
          ) )
    

    When a user uploads an image I have set up that it will prefix the file with name "profile" followed by the ID number along with the extension they uploaded. This is working just fine and what I want is for database to capture that file name structure that I just used to save the file.

    If you look at the above block code within the return statement you will notice that I concatenated. Is there any way I can save that info into the database?

    I just ran a test using the above code and it put into the database the URL/profile__ID__.EXTN without populating what those values are.

    Does this make sense? Is there anyway I can save prefix, ID, and EXT and concatenate that into a URL?

    Thanks for your help so far.

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    That's not directly possible I'm afraid. The reason is that the ID doesn't exist before the data is written to the database - so it can't be used before that!

    There are a couple of options though:

    1. Perhaps the easiest is to store the extension and path separately. You've already got the id, so you could combine them together on the client-side to get the full path.
    2. Use a database trigger to create the value of the urlToImage column based on the new data in the row.
    3. Use a custom action for the upload. That way you will have the id and can update the row with the completed url.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Allan,

    Thank your the response. It's unfortunate that it can't be done. So if I am understanding you correctly, in my pasted code from my previous response the Upload call happens after the DB?

    Out of curiosity, can I have my column "urlToImage" get updated after the users clicks the "Create" button. Maybe that way I can get what I want? Further, this may help too, because what if the user decides they don't want to upload and click the "X" to close the popup.

    Finally, I just want to mention that I appreciate the alternative suggestions, but I don't know what you mean by them. Are there any tutorials on how to do 1 & 3?

    Can I do suggestion #3 from my idea that I had? That when the user clicks "Create" I can update my "urlToImage" field with the data that I wanted?

    Thanks for the help thus far.

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    in my pasted code from my previous response the Upload call happens after the DB?

    The parameters defined in the db array are the ones used to insert into the table. So my point is that you can't use the id in that, since you don't know the id until the insert happens. You'd need to wait for the insert to happen, causing the database to generate the id (assuming it is an auto incrementing sequence) and then use that.

    can I have my column "urlToImage" get updated after the users clicks the "Create" button. Maybe that way I can get what I want?

    That's not actually the problem here. The point is that you want to use the id in a custom file name, before the id is available. That doesn't work I'm afraid. You'd need to use one of my suggestions above.

    Are there any tutorials on how to do 1 & 3?

    Renderers are documented here. Basically, you use a Javascript function to combine the data from the row into what you want your user to see (including HTML).

    The link I gave above is currently the only documentation for option #3. I'll see if I can put together a little example of that as I can see it would be a useful thing to be able to do!

    Can I do suggestion #3 from my idea that I had? That when the user clicks "Create" I can update my "urlToImage" field with the data that I wanted?

    No. Ignore the create button! By that time it to too late :smile:. You would need to use a custom upload method (the 'move file' stuff in the docs there), with an added call to update the database. I'll show an example of that tomorrow.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    Thanks for the response. Any additional tutorials or documentation that you can use to help me out would be greatly appreciated.

    I am still trying to figure how the renderer (client side) will be able to tell the DB (server side) the change in the file name. So I am looking forward to your tutorial on how this is all going to work out.

    Thanks!

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin
    Answer ✓

    Sorry for the delay in replying!

    This is a bit of a hack between your code above and the example in the documentation - you might want to check the paths etc before actually using it!

    Field::inst( 'image' )
        ->upload(
            Upload::inst( function ( $file, $id ) {
                $extn = pathinfo( $file['name'], PATHINFO_EXTENSION ); // get extension
                $webPath = '/images/profile'.$id.'.'.$extn;
                $serverPath = $_SERVER['DOCUMENT_ROOT'] . $webPath;
    
                // Save the file on the server
                move_uploaded_file( $file['tmp_name'], $serverPath );
    
                // Set the `urlToImage` in the database
                $db->update(
                    'image',
                    array(
                        'urlToImage' => $webPath
                    ),
                    array( 'id' => $id )
                );
    
                return $id;
            } )
                ->db( 'image', 'id', array(
                    'fileName' => Upload::DB_FILE_NAME,
                    'fileSize' => Upload::DB_FILE_SIZE
                ) )
        )
        ->setFormatter( 'Format::nullEmpty' );
    

    It uses the database methods that the Editor PHP class uses to update the database. The API for that is documented here.

    Regards,
    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Allan,

    Need your help again. I feel like we are almost there. The solution that you have provided nearly works. I just don't know how to make the db->update to work. That is the only part of the solution I don't know how to configure just yet. For completeness sake I am reposting the complete code with your suggestions to make sure we are both on the same page here.

    Field::inst( 'Table.urlToImage' )
                                ->upload( Upload::inst( function ( $file, $id ) {
                                        $extn = pathinfo( $file['name'], PATHINFO_EXTENSION ); // get extension
                                        $webPath = '/images/.../profile' . $id . '.' . $extn;
                                        $serverPath = $_SERVER['DOCUMENT_ROOT'] . $webPath;
                                        $dest = $_SERVER['DOCUMENT_ROOT'] . '/images/.../';
                             
                                        error_log("Step 1\nExtension: " . $extn . "\nWeb Path: " . $webPath . "\nServer Path: " . $serverPath . "\n" , 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
                             
                                        // Save the file on the server
                                        move_uploaded_file( $file['tmp_name'], $dest );
                             
                                        error_log("Step 2\nMove File Success! ". $dest . "\n", 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
                                        
                                        // Set the `profile_url` in the database
                                        $db->update(
                                            'Table',
                                            array(
                                                'urlToImage' => "http://www.example.com" . $webPath
                                            ),
                                            array( 'ID' => $id )
                                        );
                             
                                        error_log("Step 3\nUpload Success! ". "http://www.example.com" . $webPath . "\n", 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
                                        return $id;
                                    } )
                                    ->db( 'Table', 'ID', array(
                                        'urlToImage' => Upload::DB_FILE_NAME
                                    ) )
                                    ->validator( function ( $file ) {
                                        return$file['size'] >= 5000000 ?
                                            "Files must be smaller than 5 MB" :
                                            null;
                                    } )
                                    ->allowedExtensions( array( 'png' ), "Please upload an image" )
                                )
                        )
    

    From my error logs every time I run this piece of code it fails on the db->update as I mentioned previously. With that being said there is a part of me that is thinking the "where' clause might be the culprit on this. It's just a feeling that I have. One more thing I am using the Parent/Child Editor found from this blog entry (https://datatables.net/blog/2016-03-25) and have made my tables accordingly to fit that model. With that being said could that be the reason for my "where" clause from the db->update to fail? Like I said this is just a thought that i had.

    Thanks for the help so far I can tell it's nearly there.

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin
    Answer ✓

    Change:

    function ( $file, $id ) {

    To be

     function ( $file, $id ) use ( $db ) {
    

    That's how PHP's anonymous functions can access external variables. Its a bit frustrating when you are used to Javascript, but I think it was the only way they could make it work with their closure model.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Thank you Allan that did the trick.

    Now I just need to get the client side to be aware of this new change when they uploaded the image because it's stating that there was an error in the upload when there was not.

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin
    Answer ✓

    What is the JSON that the server is returning for the upload request?

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Thank you Allan. That pointed in the right direction. It seems that my "move_uploaded_file" within my php was throwing an error. It was an easy fix to make.

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Sorry Allan. Just noticed an issue in which I have no clue what to do to correct.

    In my opinion all that we have done is working just fine. My only concern is when click the "Create" button after I upload an image. What ends up happening is when I click the "Choose a file..." it creates a new database entry with the correct information within that field as I wanted it to be (thanks for the help on that). However, there is another database entry with the other fields and the picture field has only the ID number in it's field.

    Not sure why it's create another database entry. Why doesn't it just update new entry once the upload is successful.

    Maybe I can delay the upload until the creation has been completed? I really don't know what to do about this. Any suggestions would be greatly appreciated.

    Thank you.

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    What should be happening is that the file is uploaded immediately and a new record is made on the files table at that time. The server will then return the id of the new file to the client, and it can use that id to display the file in some way (which is configurable).

    The new record in the file table would only be referenced from another database table when you actually save the new row.

    To be able to say much more than that, I'd need a link to the page so be able to see what is happening.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0
    edited December 2016

    Hi Allan,

    I wish it was doing what you are describing because that is exactly what I wanted. This extra entry is making this project a bit harder than I would like it to be.

    In order for me to provide you with a look I can only show you a temporary showing. I have created a separate page that I will put up until Wednesday, Jan 4 and I will be terminating that page after that. This is not meant to be used publicly but I will allow it to be open for you until then.

    Hopefully, this gives you enough information as to what the cause is of the problem. If we need to do a skype session or something just let me know and I can arrange it. Just in case you need to look at the DB or any of the server side code.

    Thank you.

    Edit:
    Forgot to mention the URL of the temp page: http://www.fifth-cloud.com/temporarypage/

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    I am just checking to see if you needed more time to view what is causing this strange behavior? If we need to do a skype session or something like that I can arrange that to. Just let me know what you need to help figure out what the cause of this problem is.

    Thank you.

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    Hi,

    Sorry for the delay in getting back to you on this.

    Could you send me the exact PHP code you are using for the upload (including the Upload::inst part? It looks like the server doesn't quite match the code shown above (no mention of profile_url for example) and I'd like to cross check it exactly.

    Could you also add the $id to one of your debug messages. Then upload a new image to the server from your web page and show me the log messages and the JSON response from the server (i.e. what the browser sees).

    Sorry for all the requests - but hopefully that will be enough to identify the issue.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    I am not able to give you everything you have requested because the site that will be using this DataTable will be going live quite soon. I prefer not to reveal all the minute details about this project publicly. If you still feel after my explanation of problem that more information is needed I do not mind setting up a join me session that gives you access to see my screen.

    I will do my best to explain the situation by providing the receipts that you mentioned I should be capturing.

    Upon, the initial upload the Network Tab has reported this...
    {"data":[]....,"upload":{"id":"38"}}

    The "..." is meant that more information is there, but I don't think it's related to what you need to know. As you can see the ID comes as 38. My error log states this...

    Upload Overwrite ID: 38

    What this means is that when the image gets uploaded and we rename it within that function the $id that gets reported is 38. The database confirms this that the correct information for row of ID 38 has the uploaded field with the correct file name as I desire it to be. The rest of the fields are NULL as I have to click the "Create" button.

    Clicking the create button I get this from the Network Tab...
    {"data":[{"DT_RowId":"row_39","HairStyleLibrary":{"name":"1-7-2017","field1":"SampleText","field2":"SampleText","field3":"SampleText","field4":"SampleText","field5":"Style1","field6":"SampleText","field6":"1","field7":"SampleText","MyUploadedImageField":"38"}}]}

    The field called "MyUploadedImageField" is the field where I uploaded my image and now you can see that the value it puts is "38" which is not what I wanted. Another bit of information is you will notice that DT_RowId states "row_39" if that means that it has created a new row with a new id then I don't want that.

    Looking at the DB confirms this new row with ID 39. My field that I modified is called "38" which is incorrect. Row with ID 38 has the correct information for the uploaded image, but all the other fields remain as NULL which is not what I want.

    I hope this is enough information is helpful to troubleshoot what is going on. If you need more info as I stated before I have no problem with setting up a join me session (https://www.join.me/).

    Thanks again Allan and I appreciate your patience in this in helping me figure out where I went wrong.

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    I was just wondering if you had any additional thoughts about this?

    Should I setup a join.me session?

    Let me know how we should proceed about this.

    Thank you!

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    Perhaps you might think about about paying for Allan's time.
    https://datatables.net/support/#Quick-Support

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    Hi,

    Sorry for the delay in getting back to you about this.

    Looking at the page again, the first thing I notice is that:

    console.log(hStylesTable.file( 'HairStyleLibrary', file_id ).web_path);
    

    is giving undefined because there is now web_path property for that object:

                "41": {
                    "ID": "41",
                    "profile_url": "http:\/\/www.fifth-cloud.com\/images\/salons\/profile41.png"
                }
    

    If you used profile_url instead of web_path, it would show the path given, and you could then use that in the img.

    The field called "MyUploadedImageField" is the field where I uploaded my image and now you can see that the value it puts is "38" which is not what I wanted.

    What is the actual name of that field in the link you gave above? thumb_url? If so, I would suggest you need to get that from a left join.

    Another bit of information is you will notice that DT_RowId states "row_39" if that means that it has created a new row with a new id then I don't want that.

    It sounds like you are inserting the image into the same table as the master record. Is that correct? Without the full and unmodified PHP it is difficult to tell, but it sounds like the upload is inserting into the table (probably) called HairStyleLibrary and also inserting the data for the row into the same table.

    I would recommend against that. Because the upload is async to the rest of the form, it would always result in two records. Instead, I would suggest using a second table for the images and their meta information and do a left join from the main table to the image table.

    This is the approach that is detailed in the manual and used in the Editor examples.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0
    edited January 2017

    Allan,

    Thank you for response.

    If you used profile_url instead of web_path, it would show the path given, and you could then use that in the img.

    Your suggestion about my image path was a good catch. Now my image does show up.

    Perhaps you might think about about paying for Allan's time.

    tangerine,
    Before I purchased the Editor I had a discussion with Allan about his current pricing model. Back then I knew I wouldn't need a year worth of support, but something less than that. When I looked at your link you provided it seems as though Allan has finally caved in and has a quick help system, which at the rate I am going to get this resolved I will most likely purchase that if after this I am no closer to my solution. I appreciate all the help Allan has been providing me, but I guess there is something I am just not getting with this Editor. But thanks for pointing out to me that the Quick Help has been introduced.

    What is the actual name of that field in the link you gave above? thumb_url? If so, I would suggest you need to get that from a left join.

    I have spent some time updating my Temporary Page to have sample code for both client and server. Please review both scripts in it's entirety. Maybe something I have done or have not done is causing this problem.

    Client Side Script

    <link rel="stylesheet" type="text/css" href="../wp-content/mu-plugins/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../wp-content/mu-plugins/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../wp-content/mu-plugins/css/select.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="../wp-content/mu-plugins/css/editor.dataTables.min.css">
    <script type="text/javascript" charset="utf8" src="../wp-content/mu-plugins/js/jquery.js"></script>
    <script type="text/javascript" charset="utf8" src="../wp-content/mu-plugins/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" charset="utf8" src="../wp-content/mu-plugins
    /js/dataTables.editor.min.js"></script>
    <script type="text/javascript" charset="utf8" src="../wp-content/mu-plugins/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" charset="utf8" src="../wp-content/mu-plugins/js/dataTables.select.min.js"></script>
    <table id="main" class="display">
      <thead>
        <tr>
          <th>name</th>
          <th>text1</th>
          <th>text2</th>
          <th>text3</th>
          <th>text4</th>
          <th>text5</th>
          <th>text6</th>
          <th>text7</th>
          <th>text8</th>
        </tr>
      </thead>
    </table>
    <table id="library" class="display">
      <thead>
        <tr>
          <th>name</th>
          <th>image1</th>
          <th>image2</th>
          <th>image3</th>
          <th>image4</th>
          <th>text1</th>
          <th>text2</th>
          <th>image5</th>
          <th>text3</th>
        </tr>
      </thead>
    </table>
    <script type="text/javascript">
    var editor; // use a global for the submit and return data rendering in the examples
    var mainEditor;
    var libraryEditor;
    var mainTable;
    var libraryTable;
    $(document).ready(function() {
    mainEditor = new $.fn.dataTable.Editor( {
            "ajax": { 
                    url:"../wp-content/mu-plugins/sample.php",
                    data: function ( d ) {
                        d.s_lists="true";
                    }
            },
            "table": "#main",
            "fields": [ {
                    "label": "Name:",
                    "name": "name"
                }, {
                    "label": "Text 1:",
                    "name": "text1"
                }, {
                    "label": "Text 2:",
                    "name": "text2"
                }, {
                    "label": "Text 3:",
                    "name": "text3"
                }, {
                    "label": "Text 4:",
                    "name": "text4"
                }, {
                    "label": "Text 5:",
                    "name": "text5"
                }, {
                    "label": "Text 6:",
                    "name": "text6"
                }, {
                    "label": "Text 7:",
                    "name": "text7"
                }, {
                    "label": "Text 8:",
                    "name": "text8"
                }, {
                    "label": "Token:",
                    "name": "UserID",
                    "type": "hidden"
                }
            ]
        } );
    mainEditor.on('preSubmit', function (e, mode, action) {
                mode.data.row_3.UserID = "[insert_php]$current_user = wp_get_current_user(); echo $current_user->ID; [/insert_php]";
        });
    mainTable = $('#main').DataTable( {
            dom: "Bfrtip",
            ajax: {
                url: "../wp-content/mu-plugins/sample.php",
                dataType: "json",
                type: "POST",
                data:{
                    "s_lists":"true"
                }
            },
            columns: [
                { data: "name", title:"Name" },
                { data: "text1", title:"Text 1" },
                { data: "text2", title:"Text 2" },
                { data: "text3", title:"Text 3" },
                { data: "text4", title:"Text 4" },
                { data: "text5", title:"Text 5" },
                { data: "text6", title:"Text 6" },
                { data: "text7" },
                { data: "text8" }
            ],
            select: { style: 'single'},
            buttons: [
                { extend: "create", editor: mainEditor },
                { extend: "edit",   editor: mainEditor },
                { extend: "remove", editor: mainEditor }
            ]
        } );
    libraryEditor = new $.fn.dataTable.Editor( {
          "ajax": {
              url:"../wp-content/mu-plugins/sample.php",
              data: function ( d ) {
                var selected = mainTable.row( { selected: true } );
                if ( selected.any() ) {
                    d.selectedMain = selected.data().ID;
                    d.hLibrary="true";
                }
              }
            },
            "table": "#library",
            "fields": [ {
                    "label": "Name:",
                    "name": "Library.name"
                }, {
                    "label": "Image 1:",
                    "name": "Library.image1",
                    "type": "upload",
                    "display": function ( file_id ) {
                        console.log(libraryTable.file( 'Library', file_id ).image1);
                        console.log(file_id);
                        return '<img src="' + libraryTable.file( 'Library', file_id ).image1+ '"/>';
                    },
                    "clearText": "Clear",
                    "noImageText": 'No image'
                }, {
                    "label": "Image 2:",
                    "name": "Library.image2"
                }, {
                    "label": "Image 3:",
                    "name": "Library.image3"
                }, {
                    "label": "Image 4:",
                    "name": "Library.image4"
                }, {
                    "label": "Text 1:",
                    "name": "Library.text1"
                }, {
                    "label": "Text 2:",
                    "name": "Library.text2"
                }, {
                    "label": "Image 5:",
                    "name": "Library.image5"
                }, {
                    "label": "Text 3:",
                    "name": "Library.text3"
                }, {
                    "label": "",
                    "name": "Library.MainID",
                    "type": "hidden"
                }
            ]
        } );
    libraryTable= $('#library').DataTable( {
            dom: "Bfrtip",
            ajax: {
                url: "../wp-content/mu-plugins/sample.php",
                type: "POST",
                data: function ( d ) {
                    var selected = mainTable.row( { selected: true } );
                    if ( selected.any() ) {
                        d.selectedMain= selected.data().ID;
                        d.hLibrary="true";
                    }
                    d.hLibrary="true";
                    d.load_data="[insert_php]$current_user = wp_get_current_user(); echo $current_user->ID; [/insert_php]";
                }
            },
            columns: [
                { data: "Library.name", title:"Name" },
                { data: "Library.image1", title:"Image 1", "render": function ( data, type, full, meta ) {return '<img src="'+data+'" />';} },
                { data: "Library.image2", title:"Image 2", "render": function ( data, type, full, meta ) {return '<img src="'+data+'" />';} },
                { data: "Library.image3", title:"Image 3", "render": function ( data, type, full, meta ) {return '<img src="'+data+'" />';} },
                { data: "Library.image4", title:"Image 4", "render": function ( data, type, full, meta ) {return '<img src="'+data+'" />';} },
                { data: "Library.text1", title:"Text 1" },
                { data: "Library.text2", title:"Text 2" },
                { data: "Library.image5", title:"Image 5", "render": function ( data, type, full, meta ) {return '<img src="'+data+'" />';} },
                { data: "Library.text3", title:"Image Quality" }
            ],
            select: { style: 'single'},
            buttons: [
                { extend: "create", editor: libraryEditor},
                { extend: "edit",   editor: libraryEditor},
                { extend: "remove", editor: libraryEditor}
            ]
        } );
    mainTable.on( 'select', function () {
        libraryTable.ajax.reload();
        libraryEditor.field( 'Library.MainID' )
            .def( mainTable.row( { selected: true } ).data().ID);
    } );
    mainTable.on( 'deselect', function () {
        libraryTable.ajax.reload();
    } );
    mainEditor.on( 'submitSuccess', function () {
        libraryTable.ajax.reload();
    } );
    libraryEditor.on( 'submitSuccess', function () {
        libraryTable.ajax.reload();
    } );
    } );
    </script>
    

    Server Side Script to follow....

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Server Side Script

    ```php
    <?php
    require_once(dirname(DIR) . '/DataTables-Editor/DataTables.php');
    use DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Join,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;

    global $db, $hadLoaded;
    
    $UID = isset($_POST['load_data']) ? $_POST['load_data'] : ''; 
    $editDB = isset($_POST['action']) ? $_POST['action'] : '';
    $sList = isset($_POST['s_lists']) ? $_POST['s_lists'] : '';
    $hLibrary = isset($_POST['hLibrary']) ? $_POST['hLibrary'] : '';
    $uploadPictures = isset($_POST['action']) ? $_POST['action'] : '';
    $bypass = false;
    
    if($uploadPictures == 'upload') $bypass = true;
    
    try{
    // List  for the user
    if($sList == "true"){
        $mainEditor = Editor::inst( $db, 'Main', 'ID' );
    
        $mainEditor->fields(
                Field::inst( 'ID' ),
                Field::inst( 'name' )->validator( 'Validate::required' ),
                Field::inst( 'text1' )->validator( 'Validate::required' ),
                Field::inst( 'text2' ),
                Field::inst( 'text3' )->validator( 'Validate::required' ),
                Field::inst( 'text4' )->validator( 'Validate::required' ),
                Field::inst( 'text5' )->validator( 'Validate::required' ),
                Field::inst( 'text6' )->validator( 'Validate::required' ),
                Field::inst( 'text7' ),
                Field::inst( 'text8' ),
                Field::inst( 'UserID' )
            )
            ->join(
            Mjoin::inst( 'Library' )
                ->link( 'Main.ID', 'Library.MainID' )
                ->fields(
                    Field::inst( 'ID' )
                )
            )
            ->process( $_POST )
            ->json();
    }
    
    //if($wpUserID != '' || $editDB == 'edit' || $editDB == 'create'){
    else if($hLibrary == "true" || $uploadPictures == 'upload'){
        if ( (! isset($_POST['selectedMain']) || ! is_numeric($_POST['selectedMain'])) && $hLibrary == "true") {
            echo json_encode( [ "data" => [] ] );
        }
        else if(($hLibrary == "true" || $uploadPictures == 'upload') && (is_numeric($_POST['selectedMain']) || isset($_POST['selectedMain'])) || $bypass ) {
            try{
                $pathToImg = 'http://www.fifth-cloud.com/images/salons/';
                $mediaLibrary = Editor::inst( $db, 'Library', 'ID' );
                $mediaLibrary->fields(
                        Field::inst( 'Library.name' )->validator( 'Validate::required' ),
                        Field::inst( 'Library.image2' ),
                        Field::inst( 'Library.image3' ),
                        Field::inst( 'Library.image4' ),
                        Field::inst( 'Library.text1' ),
                        Field::inst( 'Library.text2' ),
                        Field::inst( 'Library.image5' ),
                        Field::inst( 'Library.MainID' ),
                        Field::inst( 'Library.text3' ),
                        Field::inst( 'Library.image1' )
                            ->upload( Upload::inst( function ( $file, $id ) use ( $db ) {
                                    $extn = pathinfo( $file['name'], PATHINFO_EXTENSION ); // get extension
                                    $fileName = 'image1' . $id . '.' . $extn;
                                    $webPath = '/images/salons/' . $fileName;
                                    $serverPath = $_SERVER['DOCUMENT_ROOT'] . $webPath;
                                    $dest = $_SERVER['DOCUMENT_ROOT'] . '/images/salons/';
    
                                    // Save the file on the server
                                    move_uploaded_file( $file['tmp_name'], $dest . $fileName );
    
                                    // Set the `image1` in the database
                                    $db->update(
                                        'Library',
                                        array(
                                            'image1' => "http://www.fifth-cloud.com" . $webPath
                                        ),
                                        array( 'ID' => $id )
                                    );
    
                                    return $id;
                                } )
                                ->db( 'Library', 'ID', array(
                                    'image1' => Upload::DB_FILE_NAME
                                ) )
                                ->validator( function ( $file ) {
                                    return$file['size'] >= 5000000 ?
                                        "Files must be smaller than 5 MB" :
                                        null;
                                } )
                                ->allowedExtensions( array( 'png' ), "Please upload an image" )
                            )
                    )
                    ->leftJoin( 'Main', 'Main.ID', '=', 'Library.MainID' )
                    ->where( 'MainID', $_POST['selectedMain'] )
                    ->process($_POST)
                    ->json();
            } catch (Exception $ex){
                error_log("Caught exception: ".  $ex->getMessage(). "\n", 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
            }
        }
        else{
            echo json_encode( [ "data" => [] ] );
        }
    }
    
    }catch (Exception $ex){
        error_log("Caught exception: ".  $ex->getMessage(). "\n", 3, $_SERVER['DOCUMENT_ROOT'] . '/.../errorLog.txt');
    }
    
    <?php > ``` ?>
  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    If I were to purchase the "Support 60" would that be enough for us to walk through this issue? I'm sure I am just missing something that you keep trying to tell me, but obviously I am not getting.

    Further, would that be enough for us to do a one-on-one and go more in depth about this?

    Let me know your thoughts.

    Thank you!

  • allanallan Posts: 63,552Questions: 1Answers: 10,476 Site admin

    Thank you for the code above. That shows that the problems is as I suggested above, specifically that both the upload and main editor are configured to use the same database table. In this case Library.

    There is no way to use the same table for both - the file is uploaded async to the rest of the form, so the insert done for the uploaded file is done before the new row is created for the rest of the data.

    The left join and upload documentation that I linked to above cover these points and how to use the upload with a joined table so that this issue doesn't occur.

    I'd be quite happy for you to pick up the support option, but my answer would be the same as above :smile:. You can't use the Library table for both the main editor table and the upload file table.

    Allan

  • cbasmadjiancbasmadjian Posts: 56Questions: 14Answers: 0

    Hi Allan,

    I followed the links that you have sent and it's still confusing. I have created the necessary table as you asked, but I am not getting the results I wanted. The new table has results I want, but there is no correlation between the two tables.

    The documentation that you have linked only show a snippet of code without showing the whole code like "examples" do, for example: https://editor.datatables.net/examples/advanced/upload.html

    Because of that there is a bit of code that gets assumed that a person like me should know. So I have spent a good majority of time just experimenting on what you could have possibly meant.

    With that being said, I think it's best if I were to purchase the Quick support and we can setup a time so you can walk me through what you meant from your previous reply. Once we get that working can you walk me through how to understand your documentation? I think datatables is a powerful tool, but with a steep learning curve.

    Once I purchase the Quick Support I will email you and we can setup a time to get this resolved.

    Thank you.

This discussion has been closed.