Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format/customize data in table columns using datatables server processing?

The problem is pretty straight forward. When using the basic initialization of datatables server processing only plain text is displayed on the page. Rather, it pulls EXACTLY what is in the database columns into the table columns with no additional HTML formatting.

Example: Here is an img of what HTML and CSS formatted text looks like - http://i.imgur.com/li2UMI7.png. Each column of the table has it's own styling/format. Now when datatables server processing makes a request to the server/database the results are, like I said, exactly as they are in the database. So in order to get this format as shown above I would have to put the HTML inside the database it self. IE:

<span class="label label-danger">Tag</span>

or

<span class="label bg-color-greenDark">Category Label</span>

How can I format the results being pulled from the database and into the table columns on the page? I would prefer to put only TAG in the tag column rather than the entire tag HTML that goes with it.

Is there a way to intercept the results before the hit the page, format them, then post to page?

CODE:

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "scripts/server_processing.php",

          "columnDefs": [ {
            "data": "firstname", //this name should exist in you response JSON
            "render": function ( data, type, full, meta ) {
              return '<span class="label label-danger">'+data+'</span>';
            }
          } ]

    } );
} );
like image 325
user3870816 Avatar asked Mar 16 '15 15:03

user3870816


1 Answers

use the render option in the column, something like this:

$('#example').dataTable( {
  "columnDefs": [ {
    "targets": 0,//index of column starting from 0
    "data": "column_name", //this name should exist in your JSON response
    "render": function ( data, type, full, meta ) {
      return '<span class="label label-danger">'+data+'</span>';
    }
  } ]
} );

check the docs here: DataTables columns.render.
Use data to match a property/key of a source object/array. Read the doc
Use targets if you are not using any keys. Read the doc

like image 80
Castro Roy Avatar answered Oct 16 '22 20:10

Castro Roy