Search code examples
laravel-livewirelaravel-9

Is it possible to have Livewire events in a Datatables render function


I'm trying to open a modal and populate a form field with a model value.

The button to open the modal is embedded in the datatable config js and I'm thinking Livewire is running before the table is built.

The datatable uses ajax to populate and columnDefs to configure rows.

The JS for the config of the datatable is in a @push('scripts') in the component blade file.

The (simplified) render function for the row is:

var datatable = thetable.DataTable({
    .....
    render: function (data, type, full, meta){
        return ('<a href="#" data-bs-toggle="modal" data-bs-target="#UpdateModal" wire:click="edit(25)">Edit</a>');
    },
    .....
})

Clicking the button opens the modal but no XHR is made to the components edit function.

If I create an anchor in the same blade file as "normal" html:

<a href="#" wire:click="edit({{ 25 }})">test</button>

The XHR is called as expected.

So, I'm assuming Livewire doesn't know about the button - perhaps it ran before the table was built. Is there a way to force Livewire to wait?

I have tried to emit a Livewire event instead of wire:click = also no XHR.

I have seen the couple Laravel packages for Datatables. They don't suit.


Solution

  • I got this done with emitted events and component listeners.

    jQuery's on to bind to the future elements clicks which livewire.emit the events.

    protected listeners[] in the component respond to the emitted events.