--- title: Adding a form to a Livewire component --- ## Setting up the Livewire component First, generate a new Livewire component: ```bash php artisan make:livewire CreatePost ``` Then, render your Livewire component on the page: ```blade @livewire('create-post') ``` Alternatively, you can use a full-page Livewire component: ```php use App\Livewire\CreatePost; use Illuminate\Support\Facades\Route; Route::get('posts/create', CreatePost::class); ``` ## Adding the form There are 5 main tasks when adding a form to a Livewire component class. Each one is essential: 1) Implement the `HasForms` interface and use the `InteractsWithForms` trait. 2) Define a public Livewire property to store your form's data. In our example, we'll call this `$data`, but you can call it whatever you want. 3) Add a `form()` method, which is where you configure the form. [Add the form's schema](getting-started#form-schemas), and tell Filament to store the form data in the `$data` property (using `statePath('data')`). 4) Initialize the form with `$this->form->fill()` in `mount()`. This is imperative for every form that you build, even if it doesn't have any initial data. 5) Define a method to handle the form submission. In our example, we'll call this `create()`, but you can call it whatever you want. Inside that method, you can validate and get the form's data using `$this->form->getState()`. It's important that you use this method instead of accessing the `$this->data` property directly, because the form's data needs to be validated and transformed into a useful format before being returned. ```php form->fill(); } public function form(Form $form): Form { return $form ->schema([ TextInput::make('title') ->required(), MarkdownEditor::make('content'), // ... ]) ->statePath('data'); } public function create(): void { dd($this->form->getState()); } public function render(): View { return view('livewire.create-post'); } } ``` Finally, in your Livewire component's view, render the form: ```blade