在 Blade 视图中渲染表单
设置 Livewire 组件
首先,生成新的 Livewire 组件:
php artisan make:livewire CreatePost
然后,在页面中渲染该 Livewire 组件:
@livewire('create-post')
此外,你可以使用全页 Livewire 组件:
use App\Livewire\CreatePost;
use Illuminate\Support\Facades\Route;
Route::get('posts/create', CreatePost::class);
添加表单
添加表单到 Livewire 组件类有 5 个重要步骤:
- 实现
HasForms接口并使用InteractsWithFormstrait。 - 定义公共 Livewire 属性,来保存表单数据。在我们的例子中,我们把这个属性叫做
$data,不过你可以根据需要进行命名。 - 添加
form()方法,这是你配置表单的地方。然后添加表单 Schema,并告诉 Filament 在$data属性中保存表单数据(使用statePath('data'))。 - 在
mount()中调用$this->form->fill(),初始化表单。这对于每个表单都是必不可少的,即使它没有初始化任何数据。 - 定义一个方法来处理表单提交。在我们的示例中,我们使用
create(),你也可以自己命名。在该方法内,你可以使用$this->form->getState()验证和获取表单数据。使用该方法,而不是直接获取$this->data属性,因为表单数据需要在返回前验证并转换成有效格式。
<?php
namespace App\Livewire;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Illuminate\Contracts\View\View;
use Filament\Schemas\Schema;
use Livewire\Component;
class CreatePost extends Component implements HasSchemas
{
use InteractsWithSchemas;
public ?array $data = [];
public function mount(): void
{
$this->form->fill();
}
public function form(Schema $schema): Schema
{
return $schema
->components([
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');
}
}
最后,在 Livewire 组件视图中,渲染表单:
<div>
<form wire:submit="create">
{{ $this->form }}
<button type="submit">
Submit
</button>
</form>
<x-filament-actions::modals />
</div>
NOTE
<x-filament-actions::modals /> 用于渲染表单组件 Action 模态框。这段代码可以放在 <form> 元素之外的任何地方,只要它还在 Livewire 组件内。
现在到浏览器访问该 Livewire 组件,你应该就能看到 components() 中的表单组件了。