You can use required attribute for general purpose
Aug 9, 2022
3
Level 5
Livewire validation - autofocus field - cursor shifts down
Hello,
Using Laravel 9 with bootstrap 5 I have a form that I validate with Livewire.
After validation fails, the validated field gets the error and the cursor on the field moves a bit downwards, out of the input field...
This is caused by the autofocus attribute.
Is there a way to focus on the first field of the form without autofocus?
Or remove the autofocus after validation?
My code:
The component:
use Livewire\Component;
use App\Models\RoastType;
class RoastTypeForm extends Component
{
protected array $rules = [];
public $name;
public RoastType $roastType;
public function mount(RoastType $roastType)
{
$this->roastType = $roastType;
if(!is_null($this->roastType->id)) {
$this->name = $this->roastType->name;
}
}
public function rules()
{
if(!is_null($this->roastType->id)) {
return [
'name' => 'required|string|max:30|unique:roast_types, name,' . $this->roastType->id,
];
} else { //This is what I test
return [
'name' => 'required|string|max:30|unique:roast_types',
];
}
}
public function updated($name)
{
$this->validateOnly($name);
}
public function storeRoastType()
{
$this->validate();
$roastType = [
'name' => $this->name
];
if(is_null($this->roastType->id)) {//create
RoastType::create($roastType);
$this->dispatchBrowserEvent('swal:modal', [
'type' => 'success',
'message' => 'Success',
'text' => 'The Roast Type has been created'
]);
} else { //update
RoastType::find($this->roastType->id)->update($roastType);
$this->dispatchBrowserEvent('swal:modal', [
'type' => 'success',
'message' => 'Success',
'text' => 'The Roast Type has been updated'
]);
}
return Redirect::route('roast-types');
}
public function render()
{
if(!is_null($this->roastType->id)){
$pageTitle = "Edit Roast Type";
} else {
$pageTitle = "Create a Roast Type";
}
return view('livewire.admin.roast-type.roast_type_form')->with('pageTitle', $pageTitle)->extends('layouts.admin.master');
}
}
The form:
<div>
@section('page-title') {{ $pageTitle }} @endsection
@section('breadcrumb-links')
<li class="breadcrumb-item"><a href="{{ route('admin') }}"><i class="fa fa-dashboard"></i> Dashboard</a></li>
<li class="breadcrumb-item"><a href="{{ route('roast-types') }}">Roast Types</a></li>
<li class='breadcrumb-item active'>{{ $pageTitle }}</li>
@endsection
@section('page-title') {{ $pageTitle }} @endsection
<form class="form" role="form" method="post" wire:submit.prevent="storeRoastType" novalidate>
@csrf
<div class="mb-3 required">
<label class="form-label">Name</label>
<input type="text" class="form-control @error('name') is-invalid @enderror" wire:model.lazy="name" autofocus>
@error('name')
<div class="invalid-feedback" role="alert">
<strong>Name is required</strong>
</div>
@enderror
</div>
<x-form_buttons exitRoute="{{ route('roast-types')}}"/>
</form>
</div>
Please or to participate in this conversation.