Render using formatted data, Sort using raw data in DataTables.net
Asked Answered
S

1

9

Here is a sample of my datatables config

{
    "dom"        : "rltip",
    "processing" : true,
    "serverSide" : false,
    "order"      : [ [ 1 , "desc" ] ],
    "searching"  : false,
    data: [
       { "column-a" : "Sample Data A" , "column-b" : 10 , "column-c" : "Blah Blah" },
       { "column-a" : "Sample Data B" , "column-b" : 5 , "column-c" : "Blah Blah" },
       { "column-a" : "Sample Data C" , "column-b" : 38 , "column-c" : "Blah Blah" }
    ],
    "columnDefs" : [
        {
            "targets"   : 0,
            "orderable" : false,
            "data"      : "column-a"
        },
        {
            "targets"   : 1,
            "orderable" : false,
            "data"      : "column-b"
        },
        {
            "targets"   : 2,
            "orderable" : true,
            "className" : "title",
            "data"      : "column-c"
        }
     ]
}

I wanted to format the data on display, but on sorting and other backend related stuff, i want to use the raw unformated data.

Important: I must do this on client side ( javascript ).

I already tried the render function callback on the columnDefs but it doesn't seem to work.

"render" : function( data , type , row ) {

    if ( type === "sort" )
        return data;

    // format data here
    return data; // This is a formatted data

}

What i mean about "it doesn't seem to work" is the sorting is broken, it will take in consideration the formatted data, not just the raw data.

I found this old related article but it doesnt seem to be applicable anymore to the newer version of datatables.net

https://datatables.net/forums/discussion/8249/filtering-using-the-rendered-text-however-sorting-using-the-original-value

I am using version 1.10.15

Snuggle answered 11/7, 2017 at 11:7 Comment(0)
V
34

The render function is called multiple times with different values in type. If you set the unformatted data only to the type sort, you miss other for the sorting relevant types like type. Instead handle the case of type display and return the unformatted data for any other value in type.

"render" : function( data , type , row ) {    
    if ( type === "display" )
    {
       // format data here
       return data; // This is formatted data
    }    
    return data; // This is unformatted data    
}
Viperish answered 11/7, 2017 at 14:13 Comment(4)
Damn I was almost close, Thanks for the help mate, It worked :)Snuggle
Awesome solution! Save to me lots of refactoring. Thanks!Equi
This is something that should be added to the manual because the sorting approach of the software is rather opaque.Exteriorize
OMG this just save my dayKilian

© 2022 - 2024 — McMap. All rights reserved.