FilamentF
Filament3y ago
Ash

How to inject a livewire component into form builder?

Hello to all of you beautiful human beings,

I was working on a simple resource - create form. Part of the form contains a DatePicker. The context is order processing. In most cases, the default value would be "now()" or todays date (YYYY-MM-DD). However I wanted to add a few buttons such as 'Today / Yesterday / 2 Days Ago / 3 Days Ago' that when clicked, auto populates the date picker value to be whatever date matches the button action - if no button action - then the user can anyway freely edit the form and the default is anyway now().

I have trouble finding what the best way to accomplish this. I thought initially I could create a Livewire component through the php artisan make:livewire blahblah command:

<?php

namespace App\Livewire;

use Livewire\Component;
use Carbon\Carbon;
class FulFillmentFragmentDateCompletedHelper extends Component
{

    public $date;

    public function mount(){
        $this->date = now()->toDateString();
    }

    public function setDate($label)
    {
        switch ($label) {
            case 'today':
                $this->date = now()->toDateString();
                break;
            case 'yesterday':
                $this->date = now()->subDay()->toDateString();
                break;
            case '2 days ago':
                $this->date = now()->subDays(2)->toDateString();
                break;
            case '3 days ago':
                $this->date = now()->subDays(3)->toDateString();
                break;
        }
    }

    public function render()
    {
        return view('livewire.ful-fillment-fragment-date-completed-helper');
    }
}

and a blade template:

<div>
    {{-- Date Picker --}}
    <x-filament::forms.components.date-picker wire:model="date" />

    {{-- Buttons --}}
    <div class="flex space-x-2 mt-2">
        @foreach (['today', 'yesterday', '2 days ago', '3 days ago'] as $label)
            <x-filament::button wire:click="setDate('{{ $label }}')">{{ ucfirst($label) }}</x-filament::button>
        @endforeach
    </div>
</div>


Then in my form builder I was hoping to inject Livewire::make('App\Livewire\FulFillmentFragmentDateCompletedHelper but then I realize I may need to create an entirely custom form based through livewire.

What would be the best way to achieve this? Is there a way to inline an input field based on a custom livewire component along the normal form schema or what would be the ideal way to implement something like this? Appreciate any pointers!
Was this page helpful?