You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EditFormRecord.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Abstracts\Forms;
  3. use Filament\Forms\ComponentContainer;
  4. use Filament\Forms\Concerns\InteractsWithForms;
  5. use Filament\Forms\Contracts\HasForms;
  6. use Filament\Notifications\Notification;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Livewire\Component;
  9. /**
  10. * @property ComponentContainer $form
  11. */
  12. abstract class EditFormRecord extends Component implements HasForms
  13. {
  14. use InteractsWithForms;
  15. public ?array $data = [];
  16. abstract protected function getFormModel(): Model|string|null;
  17. public function mount(): void
  18. {
  19. $this->fillForm();
  20. }
  21. public function fillForm(): void
  22. {
  23. $data = $this->getFormModel()->attributesToArray();
  24. $data = $this->mutateFormDataBeforeFill($data);
  25. $this->form->fill($data);
  26. }
  27. protected function mutateFormDataBeforeFill(array $data): array
  28. {
  29. return $data;
  30. }
  31. public function save(): void
  32. {
  33. $data = $this->form->getState();
  34. $data = $this->mutateFormDataBeforeSave($data);
  35. $this->handleRecordUpdate($this->getFormModel(), $data);
  36. $this->getSavedNotification()?->send();
  37. }
  38. protected function mutateFormDataBeforeSave(array $data): array
  39. {
  40. return $data;
  41. }
  42. protected function handleRecordUpdate(Model $record, array $data): Model
  43. {
  44. $record->update($data);
  45. return $record;
  46. }
  47. protected function getSavedNotification(): ?Notification
  48. {
  49. $title = $this->getSavedNotificationTitle();
  50. if (blank($title)) {
  51. return null;
  52. }
  53. return Notification::make()
  54. ->success()
  55. ->title($title);
  56. }
  57. protected function getSavedNotificationTitle(): ?string
  58. {
  59. return __('filament::resources/pages/edit-record.messages.saved');
  60. }
  61. }