bvfi-dev's avatar

Livewire FormObject isDirty() equivalent?

Im trying to use FormObjects for all my livewire components to reduce duplicate code, but I keep running into an issue where I need to check if the model was changed, like when in an edit form and checking if the initial state and save state are different, so that I can save on my API calls. In my Livewire Form, I have:

public function preFillEntry(User $entry):void
	{
		$entry->loadMissing('contact');
		$this->email = $entry->email;
		$this->first_name = $entry->first_name;
		$this->last_name = $entry->name;

which I call in my mount() method in my Component like so:

$this->form->preFillEntry($entry);

And then in my save() method, Id like to check if a couple of properties have changed, but of course I cant use isDirty(), so Im looking into alternatives and whats the best and optimal way around this issue?

I know i can just make an array in the FormObject, with the original state and then compare this in a custom isDirty() function that I call in the save method, but Im not sure if this is the most efficient way of doing it, since this will get very repetitive if i start introducing it in all my FormObjects

0 likes
2 replies
Auqcion's avatar
Auqcion
Best Answer
Level 1

One clean approach is to store a snapshot of the form state after preFillEntry() and compare against it later. Instead of manually coding this in every FormObject, you can abstract it once in a base Form class:

public array $original = [];

public function snapshot(): void { $this->original = $this->toArray(); }

public function isDirty(array $only = []): bool { $current = $this->toArray();

if ($only) {
    $current = Arr::only($current, $only);
    $original = Arr::only($this->original, $only);
} else {
    $original = $this->original;
}

return $current !== $original;

}

Then call $this->form->snapshot() after preFillEntry() in mount().

Now every FormObject automatically gets a reusable isDirty() without repeating logic and you can even check only specific fields.

1 like
bvfi-dev's avatar

Yea, that actually makes sense, I can just abstract and extend that, then use it instead of the form with a snapshot. Thank you for the idea

Please or to participate in this conversation.