datatables-bundle icon indicating copy to clipboard operation
datatables-bundle copied to clipboard

stateSave: true

Open mmaglia opened this issue 5 years ago • 13 comments

Hi. It happens the same to me too. I don't understand why this issue has been closed. I have tried configuring with the persist_state: "local" option and in my JS the stateSave: true option and every time I reload, the Datatable is initialized as if it were loaded for the first time. I have been able to verify that the local storage is working properly.

Originally posted by @mmaglia in https://github.com/omines/datatables-bundle/issues/27#issuecomment-677524227

mmaglia avatar Aug 20 '20 22:08 mmaglia

Hi. Sorry for not explaining the context. I added the comment that starts this problem in stateSave: true # 27. Then when I saw that it was closed I thought it best to raise as a new problem although I am not sure if it is a problem or a missing functionality or is that I am doing something wrong.

This is my controller

    public function index(Request $request): Response
    {

        $table = $this->datatableFactory->createFromType(OficinaTableType::class)->handleRequest($request);
        if ($table->isCallback()) {
            return $table->getResponse();
        }

        return $this->render('oficina/index.html.twig', ['datatable' => $table]);
    }

This is the definition of the TableType

`class OficinaTableType extends AbstractController implements DataTableTypeInterface
{
    /**
     * Configuro las columnas y sus funcionamiento de la grilla de oficina
     *
     * @param DataTable $dataTable
     * @return void
     */
    public function configure(DataTable $dataTable)
    {
        // Se agrega la primera columna en blanco para poner el checkbox
        $dataTable->add('', TextColumn::class, ['label' => '']);
        $dataTable->add('id', TextColumn::class, ['label' => '#', 'searchable' => false]);
        $dataTable->add('oficina', TextColumn::class, ['label' => 'Oficina', 'searchable' => true, 'leftExpr' => "toUpper(o.oficina)", 'rightExpr' => function ($value) {
            return '%' . strtoupper($value) . '%';
        }]);
        $dataTable->add('localidad', TextColumn::class, ['label' => 'Localidad', 'searchable' => false,  'field' => 'o.localidad', 'orderField' => 'l.localidad']);

        // Ordenes de la grilla
        $dataTable->addOrderBy('localidad', DataTable::SORT_ASCENDING);
        
        $dataTable->createAdapter(ORMAdapter::class, [
            'entity' => Oficina::class,
            'query' => function (QueryBuilder $builder) {
                $builder
                    ->select('o')
                    ->from(Oficina::class, 'o')
                    ->join('o.localidad', 'l');
            }
        ]);
    }
}

This is the JavaScript portion in my view

{% block javascripts %}
    {{ parent() }}
    <script>
        $(function() {        
            $(".alert").delay(3500).slideUp(2000);       

            var grillaOficinas = $('#oficinaList').initDataTables( {{ datatable_settings(datatable) }}, {
                searching: true,
                stateSave: true,
            })
        });
    </script>  
    
{% endblock %}   

This is my configuration file (datatables.yaml)

# Latest documentation available at https://omines.github.io/datatables-bundle/#configuration
datatables:
    # Set options, as documented at https://datatables.net/reference/option/
    options:
        lengthMenu : [10, 25, 50, 100, 250, 500, 1000, 2500]
        pageLength: 10
        dom: "B<'row' <'col-sm-6'><'col-sm-6 text-right'f><'col-sm-12' tr>><'row' <'col-sm-6'l><'col-sm-6 text-right'pi>>"

    method: POST
    
    persist_state: "local"

    template_parameters:
        # Example classes to integrate nicely with Bootstrap 3.x
        className: 'table table-striped table-bordered table-hover data-table'

    # You can for example override this to "tables" to keep the translation domains separated nicely
    translation_domain: 'messages'

    # Load i18n data from DataTables CDN or locally
    language_from_cdn: true

As I said, the page, order, filters, etc. of the DataTable are saved correctly in the local storage. However, when I reload the page, this data is overwritten with the values of a newly initialized DataTable, losing the page, order or filters previously applied.

mmaglia avatar Aug 21 '20 08:08 mmaglia

I have the same problem. Any help on this topic?

juaniAla avatar Aug 21 '20 12:08 juaniAla

No idea why this would suddenly stop working, I'll mark it as a bug.

curry684 avatar Aug 24 '20 13:08 curry684

I don't think it worked at some point, because according to the datatable.js file, the script only handles query and fragment https://github.com/omines/datatables-bundle/blob/83e57742c16a6c31bb28721fd4a81b3bfe8f27ce/src/Resources/public/js/datatables.js#L26-L33

embaya avatar Aug 28 '20 22:08 embaya

Hi guys!

I think, here is the problem. After I comment this, the stateLoad is worked, from localStorage.

Why we need this?

https://github.com/omines/datatables-bundle/blob/83e57742c16a6c31bb28721fd4a81b3bfe8f27ce/src/Resources/public/js/datatables.js#L61

CsFender avatar Feb 13 '21 15:02 CsFender

Hi @CsFender. Could you clarify a little more? I don't understand how you made it work. The reference line is uncommented.

mmaglia avatar Feb 14 '21 01:02 mmaglia

Hi @mmaglia!

For me, this condition is don't evaluates true, so the "stateLoad" event is never triggered. (Sorry, I modified the previous comment: "I uncomment this" -> "I comment this".)

CsFender avatar Feb 14 '21 07:02 CsFender

I have tried without success to deny the condition or to always force it to true if (! Object.keys (state) .length) or if ((Object.keys (state) .length) || true) and set persist_state in datatables.yaml: " local" (persist_state: "local")

Could you show me how your datatables.yaml is defined and how datatables-bundle / src / Resources / public / js / datatables.js was after the changes you applied?

Thanks a lot!

mmaglia avatar Feb 14 '21 13:02 mmaglia

If I remember correctly and look back at https://github.com/omines/datatables-bundle/commit/3a9e31edab9671799bbbd8641a0bd8d4bf5f57d8 that if differentiates between a full rebuild and a partial update. The full state is only sent for the initial rebuild, so has to be ignored otherwise.

There are some nasty chances of race conditions in this code though but I do think I remember we tackled all of them. Maybe a DT update broke something there?

curry684 avatar Feb 14 '21 20:02 curry684

Good news!

I got the "stateSave" working by making two small fixes to the code in datatables.js.

The first one, the return of 'stateLoadCallback' (line 39) instead of doing a

return null

I modified it by

return JSON.parse (localStorage.getItem ('DataTables_' + config.name + '_' + window .location.pathname));

The second one, and attending to @CsFender's comments I modified the input condition in line 61 from

if (Object.keys (state).length) {

to

if (Object.keys (state).length || true) {

Obviously, I am forcing the input condition in the evaluation of line 61. And I am completely unaware why modifying the return of the 'stateLoadCallback' function has made everything work.

I hope this information serves and facilitates those involved in the development to apply a definitive solution in a next version.

I have verified that the solution works with Datatables.js version 1.0.25 and 1.11.0 which was recently released.

I have tried setting persist_state with local and query values. Both worked as expected.

I apologize for my English. I used google translation services.

mmaglia avatar Sep 01 '21 22:09 mmaglia

Sorry. I forgot to mention that I previously tried different old versions of Datatables. I even tested the 1.10.13 released in December / 2016, prior to the 3a9e31e committee. In none of the tested versions did the stateSave work.

I think the problem could be more related to current browsers. Maybe some update to the ECMAScript level?

mmaglia avatar Sep 02 '21 19:09 mmaglia

I have the same problem. Any help on this topic?

me too

davidromani avatar Jun 28 '22 09:06 davidromani

Hello.

I don't know if you have tried the solution I mentioned in my post. It worked for me. It was about modifying only a couple of lines.

However, I decided to change the approach and ended up developing the CRUDS, and all other associated functionality, in Modal form. That way I didn't have to deal with losing filters, sorting, etc. since I never leave the page where you are viewing the Datatables data.

P.S. I'm sorry for my English. I used Google translation services to answer you. My native language is Spanish.

mmaglia avatar Jun 28 '22 21:06 mmaglia

Stale issue message

github-actions[bot] avatar Nov 22 '22 22:11 github-actions[bot]