stateLoadParams fires before my custom filter elements are created

stateLoadParams fires before my custom filter elements are created

paulh736paulh736 Posts: 11Questions: 7Answers: 0

I've got a table that pulls its data via an AJAX call to an API, and I've got a couple of custom filters that are added to the DataTable via the layout option. I've got stateSave: true, and I've defined stateSaveParams to copy the values from the custom filters into the data object, and stateLoadParams to retrieve the stored data values and use them to set the selected options on the custom filter <select> elements. I think it's saving the values of the custom filters correctly, but when the page is reloaded, it seems that the code in stateLoadParams is firing before the layout option has created my filter elements.

If I do

console.log($("#colourFilter").length);

in the stateLoadParams code, it returns zero. So my <select> elements don't exist at that point.

Am I going about this in completely the wrong way? Or is there a way I can populate the saved values back into my custom filters?

https://live.datatables.net/hoyucovi/1/

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 64,829Questions: 1Answers: 10,731 Site admin
    Answer ✓

    No, you are doing it the right way, it's just that you are starting to get into the complexities of the software :). The state has to load before DataTables can do much (i.e. page length, start record, column ordering, etc). Only once that is done can it then proceed with the initial setup based on the restored state. That includes creating elements and so on.

    So what you need to do is, when you create your filters, is check for a stored state (state.loaded()). This is exactly what I do in ColumnControl and other extensions.

    To get an API instance in your feature function you need to do:

    function (settings) {
      let dt = new DataTable.Api(settings);
      let loadedState = dt.state.loaded();
    
      if (loadedState && loadedState.colourFilter) {
        // ...
      }
    }
    

    It perhaps isn't idea, but there is a sequence of events that need to run, and that dictates other things.

    The other option, instead of handling the saved state in your feature function, is to to it in initComplete - get the API instance there and then set the value for the two select elements as they should be.

    Allan

  • paulh736paulh736 Posts: 11Questions: 7Answers: 0

    Got it working, thank you!

Sign In or Register to comment.