URGENT: New to DataTables and trying to make sense of few concepts

URGENT: New to DataTables and trying to make sense of few concepts

jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

I am building a catalog ordering application. So, through browser UI, the user enters the product code & quantity and in the table, i show product code, two different product descriptions and the quantity.

In the middle of ordering additional items, the user can go to earlier entered item and delete a row or change the quantity.

Also, there could be few product code that may be multiple items. In which case, the individual items of such bundle should show up in the table with individual descriptions and the quantity.

How can i use DataTables to build the table which can support adding, editing and deleting entries at same time.

Some code:
In HTML, i have defined a table as follows:

Group Code GroupCode Description Item Description Accessory To Ordered Qty

In Javascript, i have:
tblOrderItems = $('#XroItemsTable').DataTable({
height: "500px",
width: "98%",
scrollY: "400px",
paging: false,
editing: true,
bAutoWidth:false,
"language": { "sInfoEmpty": "No items added to the Rental Order...",
"sInfo": "Total of TOTAL item(s) added to the cart...",
"sEmptyTable": "Please add items to the order"
},
responsive: true,
"columns": [
{"orderable": false, "className":"dt-center", "width": "14%"},
{"orderable": false, "className":"dt-head-center", "width": "25%"},
{"orderable": false, "className":"dt-head-center", "width": "25%"},
{"orderable": false, "className":"dt-head-center", "width": "25%"},
{"orderable": false, "className":"dt-center", "width": "6%"}
],
"dom": '<<t>ip>'
});
In Javascript, from a form, i get Group Code and Quantiy values and after few lookups for descriptions, i insert into the table using:
tblOrderItems.row.add([
lgrpcode,
lgrptypedesc,
litemdesc,
laccessoryto,
lmoveqty
]);

Till this point, things work fine. I am able to add items.

Now, i want to make this table editable.
The code generator is giving me following sample code:
var editor = new $.fn.dataTable.Editor( {
ajax: 'php/table.lineItems.php',
table: '#lineItems',
fields: [
{
"label": "Group Code:",
"name": "group_code"
},
{
"label": "Ordered Quantity:",
"name": "ordered_quantity"
}
]
} );

var table = $('#lineItems').DataTable( {
    dom: 'Bfrtip',
    ajax: 'php/table.lineItems.php',
    columns: [
        {
            "data": "group_code"
        },
        {
            "data": "ordered_quantity"
        }
    ],
    select: true,
    lengthChange: false,
    buttons: [
        { extend: 'create', editor: editor },
        { extend: 'edit',   editor: editor },
        { extend: 'remove', editor: editor }
    ]
} );

So, here is where i need help / clarification:
- In my case, i don't have ajax source
- In the columns, i don;t understand what is "data" and what i should enter there. The "data" is also used as "name" in the editable initialization. I tried to use table column headers by it gives error#4.

Would appreciate prompt help as am stuck on it for quite a while.

Many thanks!
Jaideep

This question has an accepted answers - jump to answer

Answers

  • jr42.gordonjr42.gordon Posts: 305Questions: 2Answers: 49
    edited May 2016

    Editor only works by linking your backend server to the DataTable via ajax option. It is not like basic DataTable where you can use HTML, ajax, or js data. So where is your data being stored and how are you retrieving it?

    As far as the columns.data, when using an array of objects to populate your table, you assign an object's variable to a column using this option. It can also create an array of objects, instead of strings, for you if your table was created via HTML.

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Thanks Gordon for your response.

    Its a bummer that i need to have data on the server to use the editor.

    Like i tried to explain, i prepare the cart in a table on client side. The user is expected to edit/delete the cart.

    Once the cart is complete, the user can submit and thats when i post it to the server using ajax.

    Do you know of a way i can allow 'editable'/changeable cart?

    Best regards
    Jaideep

  • jr42.gordonjr42.gordon Posts: 305Questions: 2Answers: 49

    Well since you have your data ("model") on front-end, just use DataTables as a "view" in an MVC framework. You can put HTML inputs in each cell and attach event handlers to them ("controller").

    So you use DataTables to prepare the data and then submit the data to the server where your business logic comes into play. I know this seems like more work but trust me, DataTables has a lot of out-of-the-box features that are awesome.

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Don't get me wrong, I like what DataTables does. But I am bummed at this limitation. Can't understand why just this limitation!

    In the solution you offer, it does not allow editing of table cells, right?

  • jr42.gordonjr42.gordon Posts: 305Questions: 2Answers: 49

    There is a solution, DataTables Editor. DataTables can but it is little extra work. I mentioned this to Allan in an email, but sounds like a big enhancement.

    What I suggest, because it is what i did, utilize columns.render and render a HTML input. Then use columns.createdCell to add an attribute to the td telling you which variable was used. Now all you have to do is give all inputs single class and attach event handler. Now you have changed value and associated variable to apply it to.

    Now as far as deleting rows, utilize createdRow and add attribute to tr to help you find the associated object to delete. Then you refresh table.

    See told you, little extra work.

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Hi Gordon,

    Thanks for your input.

    You started of saying that the solution is "DataTable Editor". And that is exactly what i am trying to use for an array.

    But can't seem to figure out how to use as all examples assume there is an Ajax. Which i dont. I have an array ( cart of ordered items ) in memory which i want to make editable.

    Best regards
    Jaideep

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin

    As @jr42.gordon says, there is currently no built in way of editing a table locally only - Editor fundamentally requires a server-side data store. This will change with v1.6 which will include an option to edit a local table.

    Having said that, it is possible to do - what you would need to do is provide an ajax function that basically just takes the data submitted and returns it in the JSON required.

    I'll put an example of how this can be done for editing up on Monday, and you can then expand that to include deletion if you require.

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Hi Allan,

    That will be great. Sooner the better :)

    Thanks!
    Jaideep

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin

    This is how you can do a local edit: http://live.datatables.net/cazatabe/1/edit . Local delete just needs {} to be passed to the callback, but create is a little more tricky since it requires a new, unique, id to be created, which is normally the databases job.

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Thanks Allan. I took the code and adapted to my application as follows:

    tblOrderItemseditor = new $.fn.dataTable.Editor( {
    ajax: function ( method, url, data, success, error ) {
    if ( data.action === 'edit' ) {
    out = { data: [] };
    $.each( data.data, function ( key, val ) {
    val.id = key;
    out.data.push( val );
    } );
    success( out );
    }
    },
    idSrc: 'id',
    table: "#XroItemsTable",
    fields: [ {
    label: "Group Code:",
    name: "groupcode"
    }, {
    label: "Group Code Desc:",
    name: "groupcode_desc"
    }, {
    label: "Item Description:",
    name: "item_desc"
    }, {
    label: "Accessory To:",
    name: "accessoryto"
    }, {
    label: "Ordered Qty:",
    name: "move_qty"
    }
    ]
    } );
    tblOrderItems = $('#XroItemsTable').DataTable({
    // height : "500px",
    width : "100%",
    scrollY : "400px",
    paging : false,
    "ordering" : false,
    bAutoWidth : false,
    responsive : true,
    "language" : {
    "sInfoEmpty" : "No items added to the Rental Order...",
    "sInfo" : "Total of TOTAL item(s) added to the cart...",
    "sEmptyTable" : "Please add items to the order"
    },
    rowId:'id',
    "columns" : [ {
    "data": "groupcode",
    "orderable" : false,
    "className" : "dt-center",
    "width" : "14%"
    }, {
    "data": "groupcode_desc",
    "orderable" : false,
    "className" : "dt-head-center",
    "width" : "25%"
    }, {
    "data": "item_desc",
    "orderable" : false,
    "className" : "dt-head-center",
    "width" : "25%"
    }, {
    "data": "accessoryto",
    "orderable" : false,
    "className" : "dt-head-center",
    "width" : "25%"
    }, {
    "data": "move_qty",
    "orderable" : false,
    "className" : "dt-center",
    "width" : "6%"
    }, {
    "data": "action",
    "orderable" : false,
    "className" : "dt-center",
    "width" : " auto"
    } ],
    select: true,
    buttons: [
    { extend: "edit", editor: tblOrderItemseditor }
    ],
    "dom" : '<<t>ip>'
    });

    I get following error:
    DataTables warning: table id=XtroItemsTable - Requested unknown parameter "groupcode" for the row 3, column 0. For more information, please refer /tn/4

    Do note, at this time, the table is empty.

    Thanks!
    Jaideep

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0
    edited May 2016

    bother - I deleted your text when editing it for syntax by mistake! Sorry! My reply to your question is below.

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin

    Your row.add() call appears to be passing in an array, but your use of columns.data is telling DataTables to read data from an object. See this section of the manual for details.

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Hi Allan,

    row.add() is adding a row at a time with 5 column values.

    Since this is first time of using datatables.net, may be i am mixing up concepts.

    I am happy to sign-up for 30min / 60min of consulting if you can walk me through and get this fixed and working.

    Many thanks!
    Jaideep

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin

    Frustratingly when I deleted your message earlier I also deleted the row.add() call you showed, so I can't remember exactly what the code was, but you would need to use something like:

    table.row.add( {
      groupcode: ...,
      groupcode_desc: ...,
      ...
    } );
    

    i.e. add data in the object format that DataTables has been told to use via the columns.data option.

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0
    edited May 2016

    This helps a lot ...

    Based on it I have made necessary changes as follows:
    1. The editor & table variables:

                tblOrderItemseditor = new $.fn.dataTable.Editor( {
                ajax: function ( method, url, data, success, error ) {
                    if ( data.action === 'edit' ) {
                        out = { data: [] };
                        $.each( data.data, function ( key, val ) {
                            val.id = key;
                            out.data.push( val );
                        } );
                        success( out );
                    }
                },
                idSrc: 'id',
                table: "#XroItemsTable",
                fields: [ {
                                label: "Group Code:",
                                name: "groupcode"
                        }, {
                                label: "Group Code Desc:",
                                name: "groupcode_desc"
                        }, {
                                label: "Item Description:",
                                name: "item_desc"
                        }, {
                                label: "Accessory To:",
                                name: "accessoryto"
                        }, {
                                label: "Ordered Qty:",
                                name: "move_qty"
                        }
                ]
        } );
        
       tblOrderItems = $('#XroItemsTable').DataTable({
                // height : "500px",
                width : "100%",
                scrollY : "400px",
                paging : false,
                "ordering" : false,
                bAutoWidth : false,
                responsive : true,
                rowId:'id',
                select: true,
                "language" : {
                    "sInfoEmpty" : "No items added to the Rental Order...",
                    "sInfo" : "Total of _TOTAL_ item(s) added to the cart...",
                    "sEmptyTable" : "Please add items to the order"
                },
                "columns" : [ {
                    "data": "groupcode",
                    "orderable" : false,
                    "className" : "dt-center",
                    "width" : "14%"
                }, {
                    "data": "groupcode_desc",
                    "orderable" : false,
                    "className" : "dt-head-center",
                    "width" : "25%"
                }, {
                    "data": "item_desc",
                    "orderable" : false,
                    "className" : "dt-head-center",
                    "width" : "25%"
                }, {
                    "data": "accessoryto",
                    "orderable" : false,
                    "className" : "dt-head-center",
                    "width" : "25%"
                }, {
                    "data": "move_qty",
                    "orderable" : false,
                    "className" : "dt-center",
                    "width" : "6%"
                }, {
                    "data": "action",
                    "orderable" : false,
                    "className" : "dt-center",
                    "width" : " auto"
                } ],
              buttons: [
                          { extend: "edit",   editor: tblOrderItemseditor }
                         ],
                "dom" : '<<t>ip>'
            });
    
    1. The adding of rows now look as follows:
        function js_add_item_to_table(lgrpcode, lgrptypedesc, litemdesc,
                laccessoryto, lmoveqty) {
    
            tblOrderItems.row.add({ "groupcode":lgrpcode,                          "groupcode_desc":lgrptypedesc, "item_desc":litemdesc,
                    "accessoryto":laccessoryto, "move_qty":lmoveqty,
                    "action":'<input type="button" value = "Delete">' });
            // keep count of the items in the table.
            gbl_items_in_order++;
            // draw the table after each addition to the table
            tblOrderItems.draw();
            //
        }
    

    The comment on outcome:
    All the error messages have been resolved. HOWEVER, i still don't see edit button. Hence, cannot still edit the table entries.

    I really appreciate your help.

    Thanks!
    Jaideep

    Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin

    Thanks for the code. The reason you can't see the button is that there is no B option in your dom option:

    "dom" : '<<t>ip>'

    The B character will tell DataTables where to put the buttons in the generated DOM. Otherwise, you can use buttons().container() to get the container node and insert it into the DOM with jQuery if you prefer.

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0
    edited May 2016

    Thanks Allan!

    Now the button shows. I am able to select the row i want to edit, a form pops-up where i can make the changes. But when i try to save the form, i am getting js error:
    ReferenceError: "out" is not defined in the following lines

                    out = { data: [] };
                     $.each( data.data, function ( key, val ) {
                         val.id = key;
                         out.data.push( val );
                     } );
                     success( out );
    

    Is "out" same as my table handle "tblOrderItems" or editor handle?

    Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0
    edited May 2016

    And last question: if i also want to provide "create" and "delete" button, what changes i need to make to the code:

            ajax: function ( method, url, data, success, error ) {
                 if ( data.action === 'edit' ) {
                     out = { data: [] };
                     $.each( data.data, function ( key, val ) {
                         val.id = key;
                         out.data.push( val );
                     } );
                     success( out );
                 }
             },
    

    Thanks once again.

    Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin

    out = { data: [] };

    should be:

    var out = { data: [] };
    

    I missed that in my original code. Sorry. I suspect you might be operating in strict mode which is why my example works (which isn't in strict mode) while your own doesn't.

    Regarding delete and create, my statement above applies:

    Local delete just needs {} to be passed to the callback, but create is a little more tricky since it requires a new, unique, id to be created, which is normally the databases job.

    You should refer also to the client / server interaction to understand exactly what the function is attempting to do (i.e. provide that interface).

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Hi Allan,

    I added following code to the ajax call to return {}:
    "
    ...
    ajax: function ( method, url, data, success, error ) {
    if ( data.action === 'edit' ) {
    var out = { data: [] };
    $.each( data.data, function ( key, val ) {
    val.id = key;
    out.data.push( val );
    } );
    success( out );
    } else if (data.action === 'remove'){
    return {};
    }
    },
    ...
    "

    But this does not work. When i press the delete button, it asks for confirmation. And then it goes into infinite wait with spinning wheel.

    Would really appreciate if you can complete the example code you had earlier provided with:
    - create, edit and delete button
    - in create form, i should be able to configure which fields require user input and which field is auto populated based on values entered in previous fields
    - in the edit form, i should be able to show all fields of the row but allow changes to only to a subset of fields
    - in the inline editing, choosing which fields are allowed for changes

    Thanks!

  • allanallan Posts: 61,934Questions: 1Answers: 10,155 Site admin
    Answer ✓

    You have to call the success method with the data, just like I did for the edit case. The return {} isn't being used.

    Full support for this behaviour is coming in Editor 1.6.

    Allan

  • jadhvaryujadhvaryu Posts: 20Questions: 5Answers: 0

    Hi Allan, all!

    Would like to take moment to thank you and others who added to the discussion, helping me to get the code working.

    Really appreciate all your help, promptly given.

    Best regards
    Jaideeo

This discussion has been closed.