Search code examples
laravellaravel-livewirelivewire-powergrid

Reload or refresh Livewire Powergrid on submit of form component


I am submitting one form via Livewire submit and then I need to refresh a table(Powergrid Livewire).

in blade view, below is component for dataTable.

            <div class="table-responsive">
                <livewire:broker.brokers-api-data-table />
            </div>

Now when I submit a form, it goes to another component, AddBrokerModal and below is submit action when submit is clicked,

    public function submit()
    {
        $this->validate();
        DB::transaction(function () {
            $data = [
                'user_id' => auth()->user()->id,
                'brokerlist_id' => $this->brokerlist_id,
            ];

        BrokerApi::create($data);

        // Emit a successful event with a message
        $this->dispatch('success', __('New broker created'))->to(BrokersApiDataTable::class);
    
        $this->reset();
        });

    }

Now, I want to refresh brokers-api-data-table component when this form is submitted and successful dispatch occurs.

How to achieve that?


Solution

  • Since you are dispatching a success event to your grid, you will have a public method to manage that event:

    ....
    use Livewire\Attributes\On;
    ....
    
    final class UserTable extends PowerGridComponent
    {
        #[On('success')]
        public function manageSuccess()
        {
            /* do something*/
        }
    .....
    

    when the method manageSuccess is called a refresh of the component is executed.

    Otherwise if you don't need to "do something" other, you can simply send a pg:eventRefresh-default event instead of success (the -default ending is the default-table-name, change it as needed):

    // AddBrokerModal
    public function submit()
    {
       .....
    
       BrokerApi::create($data);
    
       $this->dispatch('pg:eventRefresh-default')->to(BrokersApiDataTable::class);
        
       $this->reset();
    }
    

    A third option is to send a more generic $refresh event:

    // AddBrokerModal::submit()
    
    $this->dispatch('$refresh')->to(BrokersApiDataTable::class);
    

    In this case I think you must add $refresh to the listeners:

    // BrokersApiDataTable
    final class UserTable extends PowerGridComponent
    {
        protected $listeners = [
          '$refresh'
        ];
    
    .....