sobitnl / livewire-forms
一个动态、响应式的 Livewire 表单组件,具有实时验证、文件上传、数组字段等功能。
README
一个具有实时验证、文件上传、数组字段等功能,且动态、响应式的 Livewire 表单组件。
-
基于 Kevin Dion 的工作 并在几个方面进行了改进
安装
请确保您已经 安装了 Laravel Livewire。
通过 Composer 安装此包
composer require sobitnl/livewire-forms
此包旨在与 Laravel 前端脚手架 一起良好工作。
如果您现在正在进行脚手架构建,则需要将 @stack('scripts')
、@livewireScripts
和 @livewireStyles
blade 指令添加到您的 resources/views/layouts/app.blade.php
文件中
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
@livewireStyles
...
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}"></script>
@livewireScripts
@stack('scripts')
此包还使用了 Font Awesome 作为图标。如果您还没有安装它,安装过程很简单
npm install @fortawesome/fontawesome-free
然后,将以下行添加到 resources/sass/app.scss
@import '~@fortawesome/fontawesome-free/css/all.min.css';
现在,您只需编译资产
npm install && npm run dev
创建表单组件
使用 make
命令
php artisan make:form UserCreateForm --model=User
这将在 app/Http/Livewire
文件夹中创建您的新表单组件。
创建组件后,您可能想编辑 fields
、success
、cancel
、saveAndStayResponse
和 saveAndGoBackResponse
方法
class UserCreateForm extends FormComponent
{
public function fields()
{
$this->addExtraButtons('btn btn-primary','logHello','hello');
$this->addExtraButtons('btn btn-secondary','slogGoodbye','goodbye');
return [
Field::make('Name')->input()->rules('required'),
];
}
// extra button methods
public function logHello()
{
logger('say hello');
}
public function logGoodbye()
{
logger('say goodbye');
}
public function success()
{
User::create($this->form_data);
}
public function saveAndStayResponse()
{
return redirect()->route('users.create');
}
public function saveAndGoBackResponse()
{
return redirect()->route('users.index');
}
public function cancel()
{
return redirect()->route('users.index');
}
}
您不必在表单组件中使用 render()
方法或担心组件视图,因为包会自动处理这些。
技巧
您可以将 FillsColumns
特性添加到您的模型中,以通过数据库列名自动创建 $fillable
。
如果您想添加额外的按钮,可以在 fields
方法内这样做。添加一个方法调用
$this->addExtraButton('btn btnPrimary','logHello','hello');
变量
- classNames:您想要附加到按钮的不同类名
- methodName:如果点击按钮将被调用。 重要: 在您的文件中创建相应的方法
- translationVar:要设置的按钮的翻译变量
使用表单组件
您可以在视图中像使用任何其他 Livewire 组件一样使用表单组件
@livewire('user-create-form')
现在,您只需更新您的表单组件类!
表单组件属性
$model
可选的 Eloquent 模型实例,附加到表单组件。此实例通过 @livewire
blade 指令传入。
示例
@livewire('user-edit-form', ['model' => $user])
在组件 success
方法中使用模型的示例
public function success()
{
$this->model->update($this->form_data);
}
$form_data
当前表单中存在的数据的数组。这些数据按字段名称键入。
示例
$name = $this->form_data['name'];
$storage_disk
一个静态属性,用于设置用于文件上传的磁盘。默认为 public
。
示例
private static $storage_disk = 's3';
或通过 .env
全局应用
FORM_STORAGE_DISK="s3"
$storage_path
一个静态属性,用于设置用于文件上传的路径。默认为 uploads
。
示例
private static $storage_path = 'avatars';
或通过 .env
全局应用
FORM_STORAGE_PATH="avatars"
表单组件方法
fields()
此方法返回用于表单的 Field
数组。
示例
public function fields()
{
return [
Field::make('Name')->input()->rules('required'),
Field::make('Email')->input('email')->rules(['required', 'email', 'unique:users,email']),
Field::make('Password')->input('password')->rules(['required', 'min:8', 'confirmed']),
Field::make('Confirm Password', 'password_confirmation')->input('password'),
];
}
声明 Field
类似于 Laravel Nova 字段的声明。 跳转到字段声明部分 了解更多。
rulesIgnoreRealtime()
此方法用于设置实时验证时忽略的规则。
示例
public function rulesIgnoreRealtime()
{
return ['confirmed', new MyCustomRule];
}
success()
此方法定义了当表单成功提交且验证通过时应该执行的操作。
示例
public function success()
{
$this->form_data['password'] = Hash::make($this->form_data['password']);
User::create($this->form_data);
}
saveAndStayResponse()
此方法定义通过 保存
按钮成功提交后的响应。
示例
public function saveAndStayResponse()
{
return redirect()->route('users.edit', $this->model->id);
}
saveAndGoBackResponse()
此方法定义通过 保存 & 返回
按钮成功提交后的响应。
示例
public function saveAndGoBackResponse()
{
return redirect()->route('users.index');
}
mount($model = null)
此方法设置表单的初始属性。如果您需要覆盖它,请确保调用 $this->setFormProperties()
。
$model
传递给表单组件的模型实例。
示例
public function mount($model = null)
{
$this->setFormProperties();
// my custom code
}
render()
此方法渲染表单组件视图。如果您需要覆盖它,请确保返回 $this->formView()
。
示例
public function render()
{
// my custom code
return $this->formView();
}
表单字段声明
使用 Field
类来声明您的表单字段。
public function fields()
{
$brand_options = Brand::orderBy('name')->get()->pluck('id', 'name')->all();
return [
Field::make('Brand', 'brand_id')->select($brand_options)->help('Please select a brand.'),
Field::make('Name')->input()->rules(['required', Rule::unique('cars', 'name')->ignore($this->model->id)]),
Field::make('Photos')->file()->multiple()->rules('required'),
Field::make('Color')->select(['Red', 'Green', 'Blue']),
Field::make('Owners')->array([
ArrayField::make('Name')->input()->placeholder('Name')->rules('required'),
ArrayField::make('Phone')->input('tel')->placeholder('Phone')->rules('required'),
])->rules('required'),
Field::make('Insurable')->checkbox()->placeholder('Is the car insurable?')->rules('accepted'),
Field::make('Fuel Type')->radio(['Gas', 'Diesel', 'Electric'])->default('Diesel'),
Field::make('Features')->checkboxes(['Stereo', 'Bluetooth', 'Navigation'])->rules('required|min:2'),
Field::make('Description')->textarea(),
];
}
make($label, $name = null)
$label
用于表单字段的标签,例如 姓名
。
$name
用于表单字段的名称。如果为 null,则使用 $label
的蛇形写法。
基本字段示例
Field::make('First Name')->input()->rules('required|min:2'),
关系字段示例
$brand_options = Brand::orderBy('name')->get()->pluck('id', 'name')->all();
return [
Field::make('Brand', 'brand_id')->select($brand_options)->rules(['required', Rule::exists('brands', 'id')]),
...
input($type = 'text')
将字段设置为 input
元素。默认为 text
。
$type
可选的 HTML5 输入类型用于输入。
示例
Field::make('Email Address')->input('email'),
content($content = '')
创建一个内容条目,您可以粘贴任何内容。
$content
您喜欢的内容
示例
Field::make('startDiv')->content('<div class="startContainer">'),
Field::make('endDiv')->content('</div>'),
file()
将字段设置为 file
输入元素。
文件字段应具有可空的 text
数据库列,并在您的模型中转换为 array
。此数组将为每个文件填充有用的信息,包括 file
、disk
、name
、size
和 mime_type
。
示例迁移
$table->text('photos')->nullable();
示例模型转换
protected $casts = ['photos' => 'array'];
示例字段声明
Field::make('Photos')->file(),
您可以使用 multiple()
方法允许选择多个文件
Field::make('Photos')->file()->multiple(),
textarea($rows = 2)
将字段设置为 textarea
元素。
$rows
用于 textarea 的行数。默认为 2
。
示例
Field::make('Description')->textarea(5),
select($options = [])
将字段设置为 select
下拉元素。
$options
用于选择的选项数组。
使用顺序数组的示例
Field::make('Colors')->select(['Red', 'Green', 'Blue']),
使用关联数组的示例
Field::make('Colors')->select(['Red' => '#ff0000', 'Green' => '#00ff00', 'Blue' => '#0000ff']),
当使用关联数组时,键将用作选项标签,值用作选项值。
checkbox()
将字段设置为 checkbox
元素。
复选框字段应具有可空的 boolean
数据库列。
示例迁移
$table->boolean('accepts_terms')->nullable();
示例字段声明
Field::make('Accepts Terms')->checkbox()->placeholder('Do you accept our TOS?')->rules('accepted'),
如果指定了 placeholder()
,则将其用作复选框标签。
checkboxes($options = [])
将字段设置为多个 checkbox
元素。
$options
用于复选框的选项数组。与 select()
方法相同。
复选框字段应具有可空的 text
数据库列,并在您的模型中转换为 array
。
示例迁移
$table->text('features')->nullable();
示例模型转换
protected $casts = ['features' => 'array'];
示例字段声明
Field::make('Features')->checkboxes(['Stereo', 'Bluetooth', 'Navigation'])->rules('required|min:2'),
radio($options = [])
将字段设置为 radio
元素。
$options
用于单选按钮的选项数组。与 select()
方法相同。
示例
Field::make('Fuel Type')->radio(['Gas', 'Diesel', 'Electric'])->default('Diesel'),
array($fields = [])
将字段设置为字段数组。
$fields
要使用的 ArrayField
数组。 跳转到数组字段声明部分 了解更多。
示例
Field::make('Owners')->array([
ArrayField::make('Full Name')->input()->placeholder('Full Name')->rules('required'),
ArrayField::make('Phone Number')->input('tel')->placeholder('Phone Number'),
]),
使用 sortable()
方法使数组字段可排序
Field::make('Owners')->array([
ArrayField::make('Full Name')->input()->placeholder('Full Name')->rules('required'),
ArrayField::make('Phone Number')->input('tel')->placeholder('Phone Number'),
])->sortable(),
default($default)
设置字段的默认值。
$default
默认值。
示例
Field::make('City')->input()->default('Toronto'),
$inputClass
希望添加到输入字段中的类。
示例
Field::make('price')->input()->inputClass('text-right'),
autocomplete($autocomplete)
设置用于字段的自动完成值。
$autocomplete
自动完成值。
示例
Field::make('Password')->input('password')->autocomplete('new-password'),
placeholder($placeholder)
设置用于字段的占位符值。
$placeholder
占位符值。
示例
Field::make('Country')->input()->placeholder('What country do you live in?'),
help($help)
设置用于字段下方的帮助文本。
$help
帮助文本。
示例
Field::make('City')->input()->help('Please enter your current city.'),
rules($rules)
设置用于字段的Laravel验证规则。
$rules
字符串或Laravel验证规则的数组。
使用字符串的示例
Field::make('Name')->input()->rules('required|min:2'),
使用数组的示例
Field::make('City')->input()->rules(['required', Rule::in(['Toronto', 'New York']), new MyCustomRule]),
view($view)
为字段设置自定义视图。对于包中未包含的更复杂的字段元素非常有用。
$view
自定义视图。
自定义视图示例文件
{{-- fields/custom-field.blade.php --}}
<div class="form-group row">
<label for="{{ $field->name }}" class="col-md-2 col-form-label text-md-right">
{{ $field->label }}
</label>
<div class="col-md">
<input
id="{{ $field->name }}"
type="text"
class="custom-field-class form-control @error($field->key) is-invalid @enderror"
wire:model.lazy="{{ $field->key }}">
@include('slivewire-forms::fields.error-help')
</div>
</div>
自定义视图传递$field
、$form_data
、$model
变量,以及任何其他公开组件属性。
自定义视图字段声明示例
Field::make('Custom Field')->view('fields.custom-field');
数组字段声明
ArrayField
与Field
略有不同。它们应在字段array()
方法内声明。它们拥有大部分相同的方法,除了file()
和array()
方法。它们还有一个columnWidth()
方法,这在Field
中不可用。
make($name)
$name
数组字段的名称,例如phone_number
。数组字段不使用标签。相反,您应指定它们的placeholder()
。
示例
ArrayField::make('phone_number')->input('tel')->placeholder('Phone Number')->rules('required'),
columnWidth($width)
可选的Bootstrap 4网格列宽,用于桌面上的数组字段。如果没有设置,则列将默认均匀地适合网格。
示例
ArrayField::make('province')->select(['AB', 'BC', 'ON'])->placeholder('Province')->columnWidth(4),
您还可以使用auto
来自动调整列宽度以适应数组字段。
ArrayField::make('old_enough')->checkbox()->placeholder('Old Enough')->columnWidth('auto'),
发布文件
发布文件是可选的。
发布表单视图文件
php artisan vendor:publish --tag=form-views
发布配置文件
php artisan vendor:publish --tag=form-config