Order datatable by value in url partial or url parameter

Order datatable by value in url partial or url parameter

mattctmattct Posts: 9Questions: 6Answers: 0

Hi,

Is there a way to alter the initial ordering of a table using a partial of a url or a value from a url parameter?

I'm calling data via ajax similar to this example: https://datatables.net/examples/ajax/objects.html

An request might be https://test.local/office or https://test.local?col=office

In which case I'd like the initial render of the data table to be ordered by office in descending.

I've read in to the datatables docs and can see how to set the order using an index value, but cannot see anything to indicate the how to use a string

$('#example').dataTable( {
    "order": [ 2, 'desc' ]
} );

Is there a way I can use a string to alter the ordering of the data, something similar to this?

$('#example').dataTable( {
    "order": [ 'office, 'desc' ]
} );

Thanks

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    Hi @mattct ,

    This blog post should help, it's demonstrating the same thing.

    Cheers,

    Colin

  • mattctmattct Posts: 9Questions: 6Answers: 0

    Hi @colin

    I've had a look and it kind of does, but I can;t see how to order by a string instead of an integer.

    The only thing I can think of is to map the strings to values:

    function search(nameKey, data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].name === nameKey) {
          return data[i].id;
        }
      }
    }
    
    function searcharray(nameKey, data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i] === nameKey) {
          return i;
        }
      }
    }
    
    var object = [{
        "name": "firstname",
        "id": 0
      }, {
        "name": "lastname",
        "id": 1
      }, {
        "name": "position",
        "id": 2
      }, {
        "name": "office",
        "id": 3
      }];
      
     var array = [
       'first', 'second', 'position', 'office'
     ];
    
    var orderObject = search('office', object);
    
    var orderArray = searcharray('office', array);
    
    console.log(orderObject);
    
    console.log(orderArray);
    
    

    And then set the order based on the returned value or a default.

    $('#example').dataTable( {
        "order": [orderArray, 'desc' ]
    } );
    
  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    Hi @mattct ,

    No, you're right, the order only takes the column index, not the column name, I missed that bit and was pointing to you towards the way to initialise the table based on the URL. If your columns are known and are fixed, you could modify the deepLink code to convert the name to the column index.

    Cheers,

    Colin

This discussion has been closed.