Search code examples
javascriptjquerydatatabledatatableswordpress-plugin-creation

Datatable adding a new row with row.add.draw() but with different content then the other rows


I am trying to add a new row to the datatable loaded by ajax, but need the content of the new row to be different then the previous rows. I am using row.add.draw() and a new row is added to the table but with the same fields as the other rows. I need the new row to have a "ADD" button instead of "EDIT" and "DEL".

Here is the columns of the table in general:

columns: [
            { data: 'mls' },
            { data: 'steet' },        
            { data: 'city' },
            { data: 'zip' },
            { data: 'country' },             
            {'data': null, 'render': function (data, type, row, meta) {
                    return '<button id="del-'+row.mls+'" class="btn btn-danger btn-xs edit_active" data-title="Delete" data-toggle="modal" data-target="#del" >Delete</button>';
                 }

            },

this is the function of row.add.draw() :

$("#cur_act_tbl").DataTable().row.add({"mls": '',"street": '',"city": '',"zip": '',"country": ''}).draw();

new row with different button


Solution

  • In your data add a type property that will tell DataTables if this is a new row or an existing one. You will need to modify your Ajax return to include this property also (but with the value "existing")

    {"mls": '',"street": '',"city": '',"zip": '',"country": '', "type": "new"}
    

    Then in DataTables you just need to check for this property and return the corresponding button.

    columns: [
        { data: 'mls' },
        { data: 'steet' },        
        { data: 'city' },
        { data: 'zip' },
        { data: 'country' },             
        { render: (data, type, row, meta) =>  {
            let btn = '';
            if(row.type == 'new') {
                btn = '<button id="add-'+row.mls+'" class="btn btn-primary btn-xs edit_active" data-title="Add" data-toggle="modal" data-target="#add">Add</button>';
            } else {
                btn = '<button id="edit-'+row.mls+'" class="btn btn-info btn-xs edit_active" data-title="Edit" data-toggle="modal" data-target="#edit">Edit</button>';
            }
            return btn;
        }
    
    ],