Editor Upload - Append row data (i.e. file_id) with ajaxData

Editor Upload - Append row data (i.e. file_id) with ajaxData

deesendeesen Posts: 9Questions: 1Answers: 1
edited August 2016 in Free community support

Hi, I have my own image-manager class in PHP and everything is working fine. Except that I want to send the actual "file_id" when uploading a file. I already found out how to add data, but I don´t know how to access the actual edited row´s data from inside "ajaxData" to pass the actual "file_id" (in below example "data.image_id") :

{
  label: 'Image:',
  name: 'image_id',
  type:'upload',
  ajax:'/?com=product&section=attribute&action=edit&id=2',
  ajaxData: function ( d ) {
    d.append( 'ajax', 'b149e4ff7305f4ffe58a44841630eb80' );
    d.append( 'old_id', data.image_id );
  }
}

Is it possible? Thanks!

Answers

  • deesendeesen Posts: 9Questions: 1Answers: 1
    edited August 2016

    Of course it is... with

    https://datatables.net/reference/api/row().index()
    https://datatables.net/reference/api/row().data()

    My solution:

    var ajaxRowId; // keeps last clicked row-index
    
    $(document).ready(function() {
      dTeditor = new $.fn.dataTable.Editor({
        ...
        fields:[
            { label: 'image:',
            name: 'image_id', 
            type:'upload', 
            ajax:'/index.php',
                ajaxData: function ( d ) {
                d.append( 'ajax', '241a203d27d78beb16b15f8c621252e9' );
                d.append( 'prev_id', table.row(ajaxRowId).data().image_id );
            },
            ...
        ]
        ...
      })
    })
    

    I am using inline-editing for text and bubble-edit for file-uploads to have error-messages, so I already catch click-events, which is filling now also ajaxRowId, the actual clicked row´s index.

    $('#attr_color').on( 'click', 'tbody td.bubbleEdit', function (e) {
        ajaxRowId = table.row( this ).index();
        dTeditor.bubble( this );
    } );
    
  • allanallan Posts: 63,353Questions: 1Answers: 10,444 Site admin

    There is no way to access the row's data from there. Consider for example when you are creating a new row. It doesn't have an id until it is submitted to the server which generates one.

    Allan

  • deesendeesen Posts: 9Questions: 1Answers: 1

    Sorry that I cannot offer access to a live-version (localhost), but it definetly works for my purposes. I am using localStorage like in my last question: https://datatables.net/forums/discussion/35994/editor-upload-how-to-add-files-array-without-initial-ajax-request

    I also added the files-object to ajaxData, so its possible to add multiple uploads to a table without changing any SQL-data, except the added images of course. I use perceptional hash so when an image is a dublicate or filename already existing, the old ID will be returned with an error-msg.

    $(document).ready(function() {
      dTeditor = new $.fn.dataTable.Editor({
        ...
        fields:[
        { label: 'image:',
        name: 'image_id',
        type:'upload',
        ajax:'/index.php',
        ajaxData: function ( d ) {
            d.append( 'ajax', '241a203d27d78beb16b15f8c621252e9' );
            d.append( 'prev_id', table.row(ajaxRowId).data().image_id );
            d.append( 'files', JSON.stringify(table.files("files") );
        }
    

    This way on server-side its very simple to update the files-array with all the new added IDs and send it back to client.

  • deesendeesen Posts: 9Questions: 1Answers: 1
    edited August 2016

    If interested, my full code without all my additional fields looks like

    var table;
    var dTeditor;
    var ajaxRowId;
    
    $(document).ready(function () {
    
        // Taken from DataTables Editor Ajax override / localStorage-example
        // Object that will contain the local state
        var todo = {};
    
        // Set up the editor
        dTeditor = new $.fn.dataTable.Editor({
            table: "#attr_color",
            fields: [{
                label: 'Image:',
                name: 'image_id',
                type: 'upload',
                ajax: '/?com=xxx&section=yyy&action=zzz&id=2',
                ajaxData: function (d) {
                    d.append('prevId', table.row(ajaxRowId).data().image_id); // Provide previous ID of image
                    d.append('files', JSON.stringify(table.files("files")));  // Provide files-array for adding files not updated in SQL-Table yet
                    d.append('ajax', '05a0dec2ba80c25bcc7ea4195bf3648e');     // Internal parameter
                },
                display: function (file_id) {
                    return '<img class="img-responsive" src="' + table.file('files', file_id).web_path + '"/>';
                },
                clearText: 'Clear',
                noImageText: 'No image'
            }],
            ajax: function (method, url, d, successCallback, errorCallback) {
                var output = {
                    data: []
                };
    
                if (d.action === 'create') {
                    // Create new row(s), using the current time and loop index as
                    // the row id
                    var dateKey = +new Date();
    
                    $.each(d.data, function (key, value) {
                        var id = dateKey + '' + key;
    
                        value.DT_RowId = id;
                        value.order = Object.keys(todo).length;
                        todo[id] = value;
                        output.data.push(value);
                    });
                }
                else if (d.action === 'edit') {
                    // Update each edited item with the data submitted
                    $.each(d.data, function (id, value) {
                        value.DT_RowId = id;
                        $.extend(todo[id], value);
                        output.data.push(todo[id]);
                    });
                }
                else if (d.action === 'remove') {
                    // Remove items from the object
                    $.each(d.data, function (id) {
                        delete todo[id];
                    });
                }
    
                // Store the latest `todo` object for next reload
                var post = JSON.stringify(todo);
                $('#attr_color_ta').val(post);
    
                // Show Editor what has changed
                successCallback(output);
            }
        });
    
        // CUSTOM BUTTONS
        // Enable/Disable Inline-editing
        var inlineMode = false;
        $.fn.dataTable.ext.buttons.triggerInline = {
            className: 'button-triggerInline',
    
            action: function (e, dt, node, config) {
                var button = $('.dt-button.button-triggerInline');
                button.toggleClass('active');
    
                if (button.is(".active")) {
                    inlineMode = true;
                    // Inline editing on click
                    $('#attr_color').on('click', 'tbody td:not(:first-child):not(.bubbleEdit)', function (e) {
                        dTeditor.inline(this);
                    });
    
                    // Inline editing on tab focus
                    table.on('key-focus', function (e, datatable, cell) {
                        dTeditor.inline(cell.index());
                    });
                } else {
                    inlineMode = false;
                    $('#attr_color').off('click', 'tbody td:not(:first-child):not(.bubbleEdit)');
                    table.off('key-focus');
                }
            }
        };
    
        // Provide files for Datatables
        $.fn.dataTable.Editor.files = JSON.parse('<?php echo json_encode($filesArray) ?>');
    
        // Bubble-Edit nessecary for file-uploads with nice error-messages
        $('#attr_color').on('click', 'tbody td.bubbleEdit', function (e) {
            if (inlineMode) {
                ajaxRowId = table.row(this).index();
                dTeditor.bubble(this);
            }
        });
    
        // Initialise the DataTable
        table = $('#attr_color').DataTable({
            responsive: true,
            dom: 'Bfrtip',
            columns: [ {
                className: ' bubbleEdit', render: function (file_id) {
                    return file_id ?
                    '<img class="img-responsive" src="' + table.file('files', file_id).web_path + '"/>' :
                        null;
                }, data: 'image_id'
            }],
            columnDefs: [
                {orderable: false, targets: [1]}
            ],
            rowReorder: {
                dataSrc: 'order',
                editor: dTeditor
            },
            keys: {
                columns: ':not(:first-child):not(.bubbleEdit)'  // Ignore BubbleEdit (File-uploads only possible via mouse-click)
            },
            select: {
                style: 'os',
                selector: 'td:first-child',
                blurable: true
            },
            buttons: [
                {extend: "create", editor: dTeditor},
                {extend: "edit", editor: dTeditor},
                {extend: "remove", editor: dTeditor},
                {extend: "triggerInline", text: 'Excel-Mode', editor: dTeditor} // Enable/Disable Inline-editing
            ]
        });
    
        table.rows.add($.map(todo, function (value, key) {
            return value;
        })).draw();
    
    });
    
This discussion has been closed.