To extract your filter form into a separate Form class in Livewire 3, you can follow a structured approach to handle the initialization and setting of values, especially for select options that come from the database. Here’s a step-by-step solution:
- Create the Form Class: Define a form class that will handle the form data and validation.
namespace App\Http\Livewire\Forms;
use Livewire\Form;
class FilterForm extends Form
{
public $trunks = [];
public function getTrunks()
{
// Fetch trunks from the database
return \App\Models\Trunk::all()->pluck('name', 'id')->toArray();
}
}
-
Initialize the Form in the Parent Component: In your parent Livewire component, initialize the form and set the select options in the
mountmethod.
namespace App\Http\Livewire;
use Livewire\Component;
use App\Http\Livewire\Forms\FilterForm;
class ParentComponent extends Component
{
public FilterForm $form;
public function mount(): void
{
$this->form = new FilterForm();
$this->form->trunks = $this->form->getTrunks();
}
public function render()
{
return view('livewire.parent-component');
}
}
- Create the Blade View: In your Blade view, bind the form properties to the select inputs.
<!-- resources/views/livewire/parent-component.blade.php -->
<div>
<form wire:submit.prevent="submit">
<select wire:model="form.trunks">
@foreach($form->trunks as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
@endforeach
</select>
<!-- Add other form fields as needed -->
<button type="submit">Submit</button>
</form>
</div>
- Handle Form Submission: Add a method in your parent component to handle form submission.
namespace App\Http\Livewire;
use Livewire\Component;
use App\Http\Livewire\Forms\FilterForm;
class ParentComponent extends Component
{
public FilterForm $form;
public function mount(): void
{
$this->form = new FilterForm();
$this->form->trunks = $this->form->getTrunks();
}
public function submit()
{
// Handle form submission
$this->validate([
'form.trunks' => 'required',
// Add other validation rules as needed
]);
// Process the form data
}
public function render()
{
return view('livewire.parent-component');
}
}
This approach ensures that your form class is cleanly separated and reusable, while still allowing you to initialize and set values from the parent component. The mount method in the parent component is used to fetch and set the select options from the database.