Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datatables: adding extra column

Scenario

I am using datatables (@version 1.9.4) for the first time to display data to the user. I succeed in retrieving the data via ajax and in binding them to the datatable.

Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.

In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.

Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:

Requested unknown parameter '5' from data source for row 0

Question

How to set custom columns? How to fill their content with HTML?


Here is my actual config.

HTML

<table id="tableCities">
    <thead>
        <tr>
            <th>country</th>
            <th>zip</th>
            <th>city</th>
            <th>district code</th>
            <th>district description</th>
            <th>actions</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

Javascript

$('#tableCities').dataTable({
    "bPaginate": true,
    "bLengthChange": false,
    "bFilter": true,
    "bSort": true,
    "bInfo": false,
    "bAutoWidth": true
    , "bJQueryUI": true
    , "bProcessing": true
    , "bServerSide": true
    , "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});

Sample Json result

{
    "aaData":
    [
        [
            "IT",
            "10030",
            "VILLAREGGIA",
            "TO",
            "Torino"
        ],
        [
            "IT",
            "10030",
            "VISCHE",
            "TO",
            "Torino"
        ]
    ],
    "iTotalRecords": 2,
    "iTotalDisplayRecords": 2,
    "iDisplayStart": 0,
    "iDisplayLength": 2
}

Edit

Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.

/* inside datatable initialization */
, "aoColumnDefs": [
   {
        "aTargets": [5],
        "mData": null,
        "mRender": function (data, type, full) {
            return '<a href="#" onclick="alert(\''+ full[0] +'\');">Process</a>';
        }
    }
 ]
like image 400
Alberto De Caro Avatar asked Nov 05 '12 12:11

Alberto De Caro


3 Answers

You can define your columns in a different way like this

"aoColumns": [
        null,
        null,
        null,
        null,
        null,
        { "mData": null }
    ]

or this

"aoColumnDefs":[
    {
        "aTargets":[5],
        "mData": null
    }
]

Here some docs Columns

Take a look at this DataTables AJAX source example - null data source for a column

Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.

Another solution/workaround could be adding that '5' parameter...

For example adding extra "" to each row

like this:

    [
        "IT",
        "10030",
        "VILLAREGGIA",
        "TO",
        "Torino",
        ""
    ],
    [
        "IT",
        "10030",
        "VISCHE",
        "TO",
        "Torino",
        ""
    ]
like image 187
Daniel Avatar answered Oct 09 '22 07:10

Daniel


Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:

https://datatables.net/examples/ajax/null_data_source.html

like image 26
Antônio Medeiros Avatar answered Oct 09 '22 08:10

Antônio Medeiros


Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.

$(document).ready(function() {
  var table = $('#userTable').DataTable( {
        "sAjaxSource": "/MyApp/proctoring/user/getAll",
        "sAjaxDataProp": "users",
        "columns": [
                    { "data": "username" },
                    { "data": "name" },
                    { "data": "surname" },
                    { "data": "status" },
                    { "data": "emailAddress" },
                    { "data" : "userId" }
                  ],
        "aoColumnDefs": [
           {
                "aTargets": [5],
                "mData": "userId",
                "mRender": function (data, type, full) {
                    return '<button href="#"' + 'id="'+ data + '">Edit</button>';
                }
            }
         ]
    } );

    $('#userTable tbody').on( 'click', 'button', function () {
        var data = table.row( $(this).parents('tr') ).data();
        console.log(data);
        $('#userEditModal').modal('show');
    });

} );
like image 6
Bilbo Baggins Avatar answered Oct 09 '22 09:10

Bilbo Baggins