namespace App\Traits;
use Filament\Actions\Action;
use Illuminate\Support\HtmlString;
trait HasDirtyState
{
protected bool $formDirty = false;
public function updatedInteractsWithForms(string $statePath): void
{
parent::updatedInteractsWithForms($statePath);
if (data_get($this->oldFormState, $statePath) !== data_get($this, $statePath)) {
$this->formDirty = true;
$this->resetCachedHeaderActions()
->dispatch('$refresh');
}
}
protected function getCancelFormAction(): Action
{
return parent::getCancelFormAction()
->visible(fn ($livewire) => $livewire->formDirty);
}
protected function getSaveFormAction(): Action
{
return Action::make('save')
->visible(fn ($livewire) => $livewire->formDirty)
->action(function () {
$this->formDirty = false;
$this->save();
$this->resetCachedHeaderActions()
->dispatch('$refresh');
})
->visible(fn ($livewire) => $livewire->formDirty);
}
public function resetCachedHeaderActions(): static
{
// Clear the page header cached actions
$this->cachedHeaderActions = [];
// Immediately rebuild them so they're available
$this->cacheHeaderActions();
return $this;
}