Reputation: 515
I tried to create a few tricks for my form "if the form fields is null or empty the submit button should be disabled".
I do this by using livewire but in my case the button it still disabled even if the form fields is filled.
livewire file :
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ExampleForm extends Component
{
public $name = '';
public $email = '';
public $password = '';
public $disabled = true;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
'password' => 'required|min:6',
];
public function updated($fields)
{
$this->validateOnly($fields);
if(!is_null($fields) && !empty($fields)) {
$this->$disabled = false;
} else {
$this->$disabled = true;
}
}
public function submitForm()
{
$validatedData = $this->validate();
Example::create($validatedData);
}
public function render()
{
return view('livewire.example-form');
}
}
in blade.php
<form wire:submit.prevent="submitForm">
<input type="text" wire:model="name">
@error('name') <span class="error">{{ $message }}</span> @enderror
<input type="text" wire:model="email">
@error('email') <span class="error">{{ $message }}</span> @enderror
<input type="password" wire:model="password">
@error('password') <span class="error">{{ $message }}</span> @enderror
<button type="submit" {{ $disabled ? 'disabled' : '' }}>Submit</button>
</form>
Upvotes: 0
Views: 1389
Reputation: 1030
As per the requirement now, the disabled
property should be set to false only if all the validation passes for the required fields.
public $disabled = true;
public function updated($fields)
{
$this->disabled = true;
$this->validate(); // this is a blocking call
$this->disabled = false; // execution will reach this line only if all passes the validation.
}
Note that, the $fields
property passed through only has the currently updated property. so we cannot use it to validateOnly
method, since it will only validate the passed property.
Upvotes: 2