Tricks

Update Main form after Relationship Manager CRUD

Aug 26, 2022
iotron
Admin panel

This trick is needed for counters like features on the main form that need to be updated after CRUD from the relation manager. The main thing to do here is to refresh the $record on the main form following a Livewire event in the Relation Manager.

Step 1: Use the lifecycle hooks in Relation Manager to emit a Livewire event.

Tables\Actions\CreateAction::make('Add')
->label('Add Stock')
->after(function ($livewire) {
// Runs after the form fields are saved to the database.
$livewire->emit('refresh');
})
->successNotificationMessage('Product Stock added!'),

Step 2: On the main form, add the event listener.

protected $listeners = ['refresh' => '$refresh'];

Step 3: Use Placeholder components for display.

Placeholder::make('Total In Stock Quantity')
->content(function () {
return $this->record->quantity;
})
avatar

Hello

Thanks for the trick, but i don't understand where i should put the event listen ?

avatar
Eren Mustafa Özdal

You will add the protected $listeners = ['refresh' => '$refresh']; event to your App\Filament\Resources\{Model}Resource\Pages\Edit{Model} class. It works well with Placeholder. However, it did not work even though I tried with another form component. For example TextInput...

avatar

Hi! in v3 doesnt work! It's returns:

Method App\Filament\Resources\ProductoResource\RelationManagers\PaqueteRelationManager::emit does not exist.

avatar

I'd found the soluction, emit becames to dispatch en Livewire 3.

avatar

It still doesn't work with Livewire 3, I think it's because $listeners is not used anymore.

avatar

This is how I managed to make it work on Filament 3:

On EditResource.php:

use Livewire\Attributes\On;
 
#[On('refreshForm')]
public function refreshForm(): void
{
parent::refreshFormData(array_keys($this->record->toArray()));
}

Then you can call it with (p.e. inside an action):

$action->getLivewire()->dispatch('refreshForm');