Add image in DataTables according to state

3

I'm going round here with DataTables and I'd like to add a status type to a% coso. If the value is img put an image and be 0 put another image in row .

    
asked by anonymous 12.08.2015 / 13:53

2 answers

1

Given that you have a data set in the data attribute at the start of the columns of your DataTable, you can use the render to modify how the plugin will render each column.

In this attribute, you can specify a function where you can define exactly which value will be mapped to which value.

Consider the example (from the documentation):

$('#example').dataTable( {
  "columnDefs": [ {
    "targets": 4,
    "data": "description",
    "render": function ( data, type, full, meta ) {
      return type === 'display' && data.length > 40 ?
        '<span title="'+data+'">'+data.substr( 0, 38 )+'...</span>' :
        data;
    }
  } ]
} );

Note that in this example there is only one column, but the same applies to an array of columns.

The function to transform the numbers 0 and 1 into an image could be something like:

function (data, type, full, meta) {
    var img = data == 0 ? 'desativado.jpg' : 'ativado.jpg';
    return type === 'display' ? '<img src="'+img+'">' : data;
}

Also note the type === 'display' comparison. This causes the image to be returned for display, but the original data is used for sorting, filtering, and so on. To change the value used in a search, for example, you can compare the value of type === 'filter' .

Finally, a related response in SOen that might be useful for reference. There you find the following example:

personTable = $("#person-table").DataTable({
    order: [1, "desc"],
    "autoWidth": false,
    ajax: {
        url: uri,
        dataSrc: "",
    },
    "columns": [
    { "data": "FirstName", "title": "Name" },
    { "data": "Address", "title": "Address" },
    { "data": "IsActive", "title": "Active" }
    ],
    "columnDefs": [
        {
            "render": function (data, type, row) {
                return row.FirstName + " " + row.LastName;
            },
            "targets": 1
        },
        {
            "render": function (data, type, row) {
                return (data === true) ? '<span class="glyphicon glyphicon-ok"></span>' : '<span class="glyphicon glyphicon-remove"></span>';
            },
            "targets": 2
        }
    ]
});

It's almost the same thing, except here using the Bootstrap icons instead of <img> tags.

    
12.08.2015 / 16:05
0

Yes it worked in full

"columnDefs": [ {
                "targets": 6,
                "data": "RESOLVIDO",
                "render": function (data, type) {
                var img = data == 0 ? 'img/close.jpg' : 'img/ok.jpg';
                return type === 'display' ? '<img src="'+img+'">' : data;
            }
    
12.08.2015 / 17:46