Adding validation messages in afterStateUpdated hook for inputs

What I am trying to do: I am trying to run validation logic that needs to run a query to detect if something else is using a specific provided identifier from a live TextInput, and add error messages if it runs into issues. I do not want it to only show on form submission, I want it to update (debounced) as input is changed. What I did: I tried throwing a ValidationException::withMessages() with data.the_key and mountedActionData.the_key in afterStateUpdated. I tried doing a $livewire->addError('the_key', 'The error message'). My issue/the error: None of the above are adding errors reactively, as I would expect it to. Code:
TextInput::make('vendor_id')
->label('Location ID')
->visible(fn (Get $get): bool => $get('type') === 'omnivore')
->required(fn (Get $get): bool => $get('type') === 'omnivore')
->afterStateUpdated(function ($record, $state, Component $livewire) {
$exists = \App\Models\LocationIntegration::query()
->where('type', \App\Enums\IntegrationType::Omnivore)
->where('vendor_id', $state)
->where('active', true)
->exists();

if ($exists) {
$livewire->addError('vendor_id', 'The provided Location ID is already in use by another location.');

return;
}
})
->partiallyRenderComponentsAfterStateUpdated([...])
->live(debounce: 500),
TextInput::make('vendor_id')
->label('Location ID')
->visible(fn (Get $get): bool => $get('type') === 'omnivore')
->required(fn (Get $get): bool => $get('type') === 'omnivore')
->afterStateUpdated(function ($record, $state, Component $livewire) {
$exists = \App\Models\LocationIntegration::query()
->where('type', \App\Enums\IntegrationType::Omnivore)
->where('vendor_id', $state)
->where('active', true)
->exists();

if ($exists) {
$livewire->addError('vendor_id', 'The provided Location ID is already in use by another location.');

return;
}
})
->partiallyRenderComponentsAfterStateUpdated([...])
->live(debounce: 500),
4 Replies
Ar Jay Marigondon
why not just make custom rule? i think its just the same. if the required() / visible() is false then the validation from the custom rule will not fire
Bennett
BennettOP4w ago
I want it to run on every state change though, and validation doesn't run on state changes, only on submission
Ar Jay Marigondon
ok got it
$livewire->addError('data.vendor_id'...
$livewire->addError('data.vendor_id'...
No description
Bennett
BennettOP4w ago
<input class="fi-input" id="mountedActionSchema0.vendor_id" required="required" type="text" wire:model.live.debounce.500="mountedActions.0.data.vendor_id">
<input class="fi-input" id="mountedActionSchema0.vendor_id" required="required" type="text" wire:model.live.debounce.500="mountedActions.0.data.vendor_id">
Is what mine renders as, it's inside a table action And doing $livewire->addError('mountedActions.0.data.vendor_id', 'Testing'); does nothing either inside afterStateUpdated

Did you find this page helpful?