编程

Livewire 表单创建器

915 2021-12-14 15:52:45

Filament Form Builder 是一个你可以用 TALL(Tailwind, Alpine.js, Laravel, and Livewire) 栈来构建表单的包。也就是说大部分创建表单的工作可以通过 PHP 和 Livewire 组件完成。

以下是文档的示例:

<?php
 
namespace App\Http\Livewire;
 
use Filament\Forms;
use Illuminate\Contracts\View\View;
use Livewire\Component;
 
class EditPost extends Component implements Forms\Contracts\HasForms
{
    use Forms\Concerns\InteractsWithForms;
 
    public Post $post;
 
    public $title;
    public $content;
 
    public function mount(): void
    {
        $this->form->fill([
            'title' => $this->post->title,
            'content' => $this->post->content,
        ]);
    }
 
    protected function getFormSchema(): array
    {
        return [
            Forms\Components\TextInput::make('title')->required(),
            Forms\Components\MarkdownEditor::make('content'),
            // ...
        ];
    }
 
    public function render(): View
    {
        return view('edit-post');
    }
}

getFormScheme() 方法返回一个字段数组,包含一系列字段类型:

  • 文本输入框(Text input)
  • 选择框(Select)
  • 多重选择器(Multi-select)
  • 复选框(Checkbox)
  • Toggle
  • 单选框(Radio)
  • 日期时间选择器(Date-time picker)
  • 文件上传(File upload)
  • 富文本编辑器(Rich editor)
  • Markdown编辑器(Markdown editor)
  • 还有更多...

同时字段可以位你表单里的每个数据定义验证规则 如 必填(required),唯一(unique),存在(exists)[于数据库中],还有其他。 示例:

Field::make('email')->unique()
Field::make('email')->unique(table: \App\Models\User::class)
Field::make('email')->unique(column: 'email_address')

你甚至可以像在Laravel内一样使用闭包或者类自定义验证规则。你可以独立使用这个包和 Livewire 配合或者作为 Filament TALL 栈的管理面板一起使用。GitHub 上可以查看其源码。