main

filamentphp/demo

Last updated at: 29/12/2023 09:42

Form.php

TLDR

This file is the Form component in the App\Livewire namespace. It extends the Livewire\Component class and implements the HasForms contract. The component is responsible for rendering a form, handling form submission, and managing form state using the Filament Forms library.

Methods

mount

The mount method is called when the component is mounted. It checks if the application is not in the local environment and aborts with a 404 error if not. It then fills the form with data.

getFormSchema

The getFormSchema method returns an array representing the schema for the form. It uses the Filament Forms library to define the form structure, including blocks and input components.

submit

The submit method is called when the form is submitted. It retrieves the state of the form and dumps it using the dd function for debugging purposes.

getFormStatePath

The getFormStatePath method returns the path to the form state. In this case, it returns the string 'data'. This path specifies where the form state is stored within the component's data property.

render

The render method returns the view that should be rendered when the component is rendered. In this case, it returns the 'livewire.form' view.

Classes

App\Livewire\Form

This class represents the Form component in the App\Livewire namespace. It extends the Livewire\Component class and implements the HasForms contract. The component is responsible for rendering a form, handling form submission, and managing form state using the Filament Forms library.

<?php

namespace App\Livewire;

use Filament\Forms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Livewire\Component;

class Form extends Component implements HasForms
{
    use InteractsWithForms;

    public $data = [];

    public function mount()
    {
        if (! app()->environment('local')) {
            abort(404);
        }

        $this->form->fill();
    }

    protected function getFormSchema(): array
    {
        return [
            Forms\Components\Builder::make('test')
                ->blocks([
                    Forms\Components\Builder\Block::make('one')
                        ->schema([
                            Forms\Components\TextInput::make('one'),
                        ]),
                    Forms\Components\Builder\Block::make('two')
                        ->schema([
                            Forms\Components\TextInput::make('two'),
                        ]),
                ]),
        ];
    }

    public function submit()
    {
        dd($this->form->getState());
    }

    protected function getFormStatePath(): ?string
    {
        return 'data';
    }

    public function render()
    {
        return view('livewire.form');
    }
}