DataTables Editor 1.5.1 Upload not working

DataTables Editor 1.5.1 Upload not working

jaredgerberjaredgerber Posts: 40Questions: 10Answers: 0
edited September 2015 in Editor

So I upgraded to Editor 1.5.1 and I got all my old functionality up and running well -- happy about that. However, when I add the Upload field to the php process function, not only does the inline editing stop working, but also the upload doesn't work.

You can see my application here, just hit the checkbox of the 1st item (Record 19). Under the documents tab , you can click NEW or attempt inline editing for fields "Description" & "Document" to see what happens during inline editing & uploading.

I checked the debugger under [network] -> [headers] and it looks like it's posting the information the same as it is in the example, but the files are just not getting uploaded. When I click [preview], I get this error:

Parse error: syntax error, unexpected '[' in /home/opes/public_html/res/Editor-PHP-1.5.1/php/Editor/Upload.php on line 297

http://data.my-ofs.com/agent/rpt_policy.php

Also, I created a table for 'files' with all the fields ... e.g., id, filename, etc. tblitem.URL_Document is my field for the file reference.

I'm not exactly sure what the problem is, but I've been at it for quite a while trying to get it to work ... comparing to the example over and over :-) Please help :-) It's got to be something simple.

Again, if I remove the upload field from the php processor, the data in the Description field saves just fine.

    // ===================================
    // EDITOR-DOCUMENTS 
    // ===================================
    
    // # 1 CONTROLS POPUP EDITOR (DEFINE POPUP FIRST)
        editordocuments = new $.fn.dataTable.Editor( {
        ajax: 'upload.php',
        //ajax: window.location.pathname + '?table=tblitem',
        table: "#documents",
        bProcessing: true,
        bServerSide: true,
        fields: [ 
        {
                label: "RecordID",  /* POLICYID */
                name: "RecordID",   /* POLICYID */
        type: "hidden",
                default: $("#PolicyID").val()  /* NEEDS TO BE CURRENT POLICYID */
            }, {
                name: "ItemTypeID",
        type: "hidden",
                default: 12
            }, {
                name: "ItemCategoryID",
        type: "hidden",
                default: 50
            }, {
                label: "Date:",
                name: "ItemDate",
        type: "hidden",
        default: itemdate  /* "2015-09-02" */
            }, {
                label: "Description:",
                name: "ItemName"
            }, {
                label: "Document Upload:",
                name: "URL_Document",
                type: "upload",
                display: function ( file_id ) {
                    return '<a href="'+tabledocuments.file( 'files', id ).webPath+'"/>Document Link</a>';
                },
                clearText: "Clear",
                noImageText: 'No document'
            }           
        ]
    } );        
    

    // # 2 CONTROLS INLINE EDITOR / DataTables columns and columnDefs objects
       var tabledocuments = $('#documents').DataTable( {
           dom: 'Bfrtilp',
               ajax: "../Library/processListObject.php?list=item&itemcategoryid=50&id="+id+"&statusid=",
        bProcessing: true,
        bDestroy: true,
        bServerSide: true,
        bSort: false,
        bFilter: false,
        pageLength: 5,
        select: {style:'os',selector: 'td:first-child'},    
        language: {
                "lengthMenu": "Display _MENU_ records per page",
                "zeroRecords": "Nothing found - sorry",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",   /*Showing page _PAGE_ of _PAGES_*/
                "infoEmpty": "No records available",
                "infoFiltered": ""}, /*(filtered from _MAX_ total records)*/  
               columns: [
            { data: null,defaultContent: '', className: 'select-checkbox',orderable: false},
                        { data: "ItemName" },
            { data: "ItemDateF", type: "display" },
            {
               data: "URL_Document",
               render: function ( file_id ) {
               return file_id ?
                 '<a href="'+tabledocuments.file( 'files', file_id ).web_path+'"/>Document link</a>' :null;},
                defaultContent: "No document", title: "Document"
            }           
               ],
        order: [ 1, 'desc' ],
        buttons: [
                { extend: "create", editor: editordocuments },
                { extend: "remove", editor: editordocuments }
            ]
    } );

```
<?php
session_start(); // start up your PHP session!

// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Upload,
DataTables\Editor\Validate;

$db = NEW mysqli($GLO_HOST_NAME, $GLO_USER_NAME, $GLO_PASS, $GLO_DB_NAME);

// DataTables PHP library
include( "../res/Editor-PHP-1.5.1/php/DataTables.php" );

Editor::inst( $db, 'tblitem', 'ItemID' )
    ->fields(
        Field::inst( 'ItemTypeID' ),
        Field::inst( 'ItemCategoryID' ),
        Field::inst( 'CompletedDate' ),
        Field::inst( 'DueDate' ),
        Field::inst( 'ItemName' ),
        Field::inst( 'Description' ),       // REQUIRED FOR NOTES, BUT NOT FOR TASKS??
        Field::inst( 'URL_Document' )
            ->setFormatter( 'Format::nullEmpty' )
            ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/uploads/__ID__.__EXTN__' )
                ->db( 'files', 'id', array(
                    'filename'    => Upload::DB_FILE_NAME,
                    'filesize'    => Upload::DB_FILE_SIZE,
                    'web_path'    => Upload::DB_WEB_PATH,
                    'system_path' => Upload::DB_SYSTEM_PATH
                ) )

// ->allowedExtensions( array( 'pdf','doc','docx','jpg' ), "Please upload a doc or pdf file" )
// ->validator( function ( $file ) { return $file['size'] >= 2000000 ? "Files must be smaller than 2MB" : null;} )
)
)
->process( $_POST )
->json();

<?php > ``` ?>

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Parse error: syntax error, unexpected '[' in /home/opes/public_html/res/Editor-PHP-1.5.1/php/Editor/Upload.php on line 297

    Thank you for pointing that out. I've used PHP 5.4 syntax by mistake there:

    $out = [];
    

    If you change it to be:

    $out = array();
    

    it will work with PHP 5.3, which is what I presume you are using if you are getting this error. That fix will be in the next release.

    Regards,
    Allan

  • jaredgerberjaredgerber Posts: 40Questions: 10Answers: 0

    Ok -- the uploading is working now -- thank you :-) The uploading is working famously.

    However, after following the example closely, there is an issue in displaying the table now -- it may be a bug in the file() function or call. Interestingly enough, the table displays fine after the upload. It just won't show when I run initially.

    The table won't display -- it's stuck on "processing..." and throws this error -- which "28" is the file id:

    Uncaught TypeError: Cannot read property '28' of undefined
    
    (anonymous function)    @   dataTables.editor.min.js:54
    t.extend.g  @   jquery.dataTables.min.js:100
    $.DataTable.columns.render  @   rpt_policy.php:921
    

    Here is the code at 921:

    columns: [
       { data: null,defaultContent: '', className: 'select-checkbox',orderable: false},
       { data: "ItemName" },
       { data: "ItemDateF", type: "display" },
       { data: "filesid",
           render: function ( file_id ) {
           return file_id ?
            '<a href="'+tabledocuments.file( 'files', file_id ).web_path+'" target=_blank>' + tabledocuments.file( 'files', file_id ).filename + '</a>' :
           null;},
        defaultContent: "No image",
        title: "Document"
       }            
    ],
    
  • jaredgerberjaredgerber Posts: 40Questions: 10Answers: 0
    edited September 2015

    Also, is there a way to use the original filename as part of the filename that is saved to the folder without adding another move / rename operation? e.g., contract_id1.pdf

    For the benefit of other users, here is the files table structure & sample records.

    Table structure:

    Field Type Null Key Default Extra
    id int(11) NO PRI NULL auto_increment
    filename varchar(255) YES NULL
    filesize int(11) YES NULL
    web_path varchar(255) YES NULL
    system_path varchar(255) YES NULL

    Sample records:

    id filename filesize web_path system_path
    1 contract.pdf 83227 /uploads/1.pdf /home/opes/public_html/uploads/1.pdf
    2 contract.pdf 83227 /uploads/2.pdf /home/opes/public_html/uploads/2.pdf
    3 contract.pdf 83227 /uploads/3.pdf /home/opes/public_html/uploads/3.pdf
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Can you tell me where I can find the upload input in your page linked above? If it click the "New" button I don't see an upload input. If I click a checkbox to select and edit a row I get taken to a different page.

    Thanks,
    Allan

  • jaredgerberjaredgerber Posts: 40Questions: 10Answers: 0
    edited September 2015

    Here is a direct link to the right page. Just click the "Documents" tab:
    http://data.my-ofs.com/agent/rpt_policy.php?id=19

    You will see that it's stuck on "Processing". That's where the error below comes up. If you click the [New] button, it will allow you to upload a file and then after submitting, you will see that the Documents refresh fine at that point.

    Uncaught TypeError: Cannot read property '29' of undefined
    
    (anonymous function) @ dataTables.editor.min.js:54
    t.extend.g @ jquery.dataTables.min.js:100
    $.DataTable.columns.render @ rpt_policy.php:920
    

    If you upload a PDF, you'll see the nifty preview come up :-)

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Thanks for the link. It looks like the file information isn't being loaded by Ajax - if you have a look at my example page you'll see a files parameter in the returned JSON (click the Ajax load tab below the table).

    I had wondered if this was use to server-side processing being enabled, but I've just tried that and it appears to work okay. However, I did notice that you have:

    ajax: "../Library/processListObject.php?list=item&itemcategoryid=50&id="+id+"&statusid=",

    But the Editor script is processing $_POST. Could you try changing your ajax option in DataTables to be:

    ajax: {
        type: 'POST',
        url: "../Library/processListObject.php?list=item&itemcategoryid=50&id="+id+"&statusid="
    },
    

    I'm not sure that will resolve the issue to be honest, but it will rule out one thing.

    Also, just to check, the file posted above is processListObject.php?

    Thanks,
    Allan

  • jaredgerberjaredgerber Posts: 40Questions: 10Answers: 0

    if you have a look at my example page you'll see a files parameter in the returned JSON (click the Ajax load tab below the table).

    Ahh -- well, that would be the problem, lol. I'm not using the Editor::inst() as my table data source because I need more server side control over the returned data sets -- I'm using SSP:Simple() with where statement in processListObject.php -- see below. I'd love to know how to do it using SSP -- but the classes don't seem to support additional tables.

    echo json_encode( SSP::simple( $_GET, $sql_details, $sTable, $sIndexColumn, $aColumns,'',$sWhere,'',$sUserMessage) );
    

    As a side note, I did isolate the Editor::Inst() for the Documents table & editor in upload.php (for testing purposes) -- and I can see the Ajax data properly formed with "data" & "files". There is a lot of rows -- so you'll need to view source to see the files data, but it's there.

    http://data.my-ofs.com/agent/upload.php

    For future reference, I'd like to know how to do it your way; however, I did solve the problem by creating my own display function -- see below.

    http://data.my-ofs.com/agent/rpt_policy.php?id=19

    editordocuments = new $.fn.dataTable.Editor( {
       ajax: window.location.pathname + '?table=tblitem',
       table: "#documents",
       bProcessing: true,
       bServerSide: true,
       fields: [ 
    {
        label: "Document Upload:",
        name: "filesid",
        type: "upload",             
        display: 
            function ( data ) {
            return get_value('qryfiles','id','preview',data);
            }, 
        clearText: "Clear",
        noImageText: 'No document',
        fieldInfo: "Upload file, then submit."
    }           
    

    Also, one more question that remains a mystery-- and may help others -- instead of just using the ID, can I include the original filename in the file that is saved to the disk? e.g., __ID__.__EXTN__

    Also, is there a way to use the original filename as part of the filename that is saved to the folder without adding another move / rename operation? e.g., contract_id1.pdf

    Full code for the benefit of others:

    Field::inst( 'filesid' )
        ->setFormatter( 'Format::nullEmpty' )
        ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/uploads/__ID__.__EXTN__' )
            ->db( 'files', 'id', array(
                'filename'    => Upload::DB_FILE_NAME,
                'filesize'    => Upload::DB_FILE_SIZE,
                'web_path'    => Upload::DB_WEB_PATH,
                'system_path' => Upload::DB_SYSTEM_PATH
            ) )
        ->allowedExtensions( array( 'pdf','doc','docx','jpg' ), "Please upload a doc or pdf file" )                 
        ->validator( function ( $file ) { return $file['size'] >= 2000000 ? "Files must be smaller than 2MB" : null;} )
    )
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    For future reference, I'd like to know how to do it your way

    The Editor libraries support server-side processing (and are actually more capable than the SSP class). It should be possible to use the Editor classes here I think.

    instead of just using the ID, can I include the original filename in the file that is saved to the disk? e.g., ID.EXTN

    Yes - You can also use __NAME__ - see the documentation. I would suggest using the Id and the name to remove the chances of files with the same name being uploaded and resulting in data loss as one would overwrite the other.

    Allan

  • jaredgerberjaredgerber Posts: 40Questions: 10Answers: 0

    Ok - I will implement future projects using the Editor libraries.

    Thanks for pointing that out on the filename. I'm not sure how I missed that. I will include the ID for sure.

This discussion has been closed.