Add Custom Controls To DataTable Rows



Background:
datatables.js is a very awesome tool that enables data to be presented in tabular format (ASP.Net developers prefer to call this grid). Its currently the best free data-to-table tool available (my personal opinion). Since I ran into it, I immediately got stuck and cannot but use it in each of my projects.

Issue:
There are several issues with datatables.js. Many of them however stem from knowledge gap, because the tool is quite robust, it would take a long time to exhaust the documentation and fully learn the plugin. In my own case, I wanted to add custom controls to each datatable row. These three controls would be for ordering the row and editing the record.

Solution:
We would need images to use as these controls. I normally get images online sometimes. Although, I find it easier to create simple icons using CorelDraw. After fetching your data, simply loop through each item to add the html tag for your control image to the element. Finally, render the datatable using the control element as the last element to the right (or as desired).

Instance:
First loop through your data to add the controls:
for (var i = 0; i < ParentMenus.length; i++) {
  var CurrentID = ParentMenus[i].Id;  
ParentMenus[i].Delete = "<img src='images/close.png' ref='" + CurrentID + "'/>";  
ParentMenus[i].MoveUp = "<img src='images/up.png' ref='" + CurrentID + "'/>";  
ParentMenus[i].MoveDown = "<img src='images/down.png' ref='" + CurrentID + "' />";  ParentMenus[i].Controls = ParentMenus[i].MoveDown + ParentMenus[i].MoveUp + ParentMenus[i].Delete;
}

Then initialize your datatable using .Controls member above as the controls column
 Moduletable = $('#tblModules').DataTable({
    "ordering": false,
    dom: 'T<"clear">lfrtip', data: ParentMenus,
    columns: [{   

      "class": 'details-control', "orderable": false, "data": null, "defaultContent": ''
                    }, 

      { "data": "PageName" }, { "data": "PageDescription" }, { "data": "Controls" } ]
        });


See a sample of what the code above generated in the picture at the top of this post. {"data" : "Controls"} above is responsible for including my images as part of the rendered data table.
Happy gridding!

Comments

Popular posts from this blog

Resize or Crop Image before Upload Using HTML5 File API

Get Creative With Data Tables: Row Click Events

Exception from HRESULT: 0x80131040