After reinit datatable his ID is changed?

After reinit datatable his ID is changed?

adriandj83adriandj83 Posts: 2Questions: 1Answers: 0
edited February 2019 in Free community support

Hello, I have a problem with custom filters and state saving. In my application all pages are loaded by AJAX request so after that I must reinit datatables on my page. With it stateLoadParams is not called so I had idea to add values for filter in the drawCallback option. This is ok if I refresh page with F5, but after load page with AJAX, datatable is reinitialized, but his ID is changed from 0 to 1 and every request this value is bigger. I mean option sInstance or sTableId. On the start, id is DataTables_Table_0, but after reinitialize table it is DataTables_Table_1, DataTables_Table_2 etc., after that i can't get was set custom filters saved in the localStorage. Is this possible to reinitialize datatable has same ID before it? If it is could you tell me how can I do this?

// Problematic ID
getInstanceLocalStorageId(instance) {
        return  `${instance.sInstance}_custom_filters_${window.location.pathname}`;
},

// Called in the stateSaveParams() - because it is called every table draw
stateSaveParams(instance) {
        if (typeof Storage !== 'undefined') {
            const form = instance.nTableWrapper.querySelector('#custom-filters-form');
            const instance_id = this.getInstanceLocalStorageId(instance);
            const custom_filters = localStorage.getItem(instance_id) != null? JSON.parse(localStorage.getItem(instance_id)) : {};

            form.querySelectorAll('input').forEach(input => {
                if (['radio', 'checkbox'].includes(input.type)) {
                    if (input.checked) {
                        custom_filters[input.name] = {
                            type: input.type,
                            value: input.value
                        };
                    }
                }
            });

            localStorage.setItem(instance_id, JSON.stringify(custom_filters));
        }
},


// Called in the drawCallback because in ajax load page stateLoadParams is not called, only after F5 page
stateLoadParams(instance) {
        const form = instance.nTableWrapper.querySelector('#custom-filters-form');
        const custom_filters = JSON.parse(localStorage.getItem(this.getInstanceLocalStorageId(instance)));

        if (custom_filters) {
            Object.entries(custom_filters).forEach(([key, value]) => {
                if (['radio', 'checkbox'].includes(value.type)) {
                    form.querySelector(`[name="${key}"][value="${value.value}"]`).checked = true;
                }
            });
        }
},

Answers

This discussion has been closed.