Default Sort Order

Default Sort Order

ESCOITESCOIT Posts: 3Questions: 1Answers: 0

We are using DataTables to display the contents of a database query. I have the sort order of the query set to descending (based on the field "ID"), however, the form always displays the results in ascending order when it first loads. Pressing the arrow icon next to the field name does re-sort it, however, we'd like it to load in descending order by default instead. How do you do that?

Here is the JS (in the Head section) that we're using to load the form:

<script type="text/javascript">//<![CDATA[    
$(document).ready(function (){
    var table = $('#example').DataTable({
        'responsive': true
    });

    // Handle click on "Expand All" button
    $('#btn-show-all-children').on('click', function(){
        // Expand row details
        table.rows(':not(.parent)').nodes().to$().find('td:first-child').trigger('click');
    });

    // Handle click on "Collapse All" button
    $('#btn-hide-all-children').on('click', function(){
        // Collapse row details
        table.rows('.parent').nodes().to$().find('td:first-child').trigger('click');
    });
});
  //]]>
  </script>

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,173Questions: 26Answers: 4,923

    Use the order option to set the default sort order.

    Kevin

  • ESCOITESCOIT Posts: 3Questions: 1Answers: 0

    @kthorngren Thanks, we did see that in the documentation, however, the documentation is pretty incomplete on that link. We already tried a number of guesses unsuccessfully before posting the question (none of these worked):

            "order": ['des']
            "order": ['desc']
            "order": [0,'desc']
    

    Can you tell me exactly what needs to be there to sort the ID column in descending order by default?

  • kthorngrenkthorngren Posts: 21,173Questions: 26Answers: 4,923
    Answer ✓

    The docs state this:

    The order must be an array of arrays, each inner array comprised of two elements:

    The docs also show the default value is [[0, 'asc']]. If you want the first column to sort descending by default then use order: [[0, 'desc']],.

    Kevin

  • ESCOITESCOIT Posts: 3Questions: 1Answers: 0

    @kthorngren That second snippet worked, THANK YOU!

This discussion has been closed.