aquanode/formation

此包已被废弃,不再维护。作者建议使用 regulus/formation 包代替。

为Laravel 5 - 8提供强大的表单构建和模型数据转换包。


README

为Laravel 5 / 6 / 7 / 8提供强大的表单构建和模型数据转换包。

Latest Stable Version License

Formation由两个相互独立但互补的系统组成,每个系统都可以独立使用

  1. 强大的表单构建器,使用PHP表单构建方法,可以自动构建表单

  2. 易于使用的数据转换基础模型,扩展Eloquent(或可选的Extended特质,用于扩展其他内容的模型)提供了许多转换数据的特性,无论是从Web服务器到客户端服务,还是将表单数据保存到数据库。

注意:所有在表单元素内显示的输入数据都将通过实体方法进行过滤。

安装

要安装Formation,请确保 regulus/formation 已添加到Laravel 5的 composer.json 文件中。

"require": {
	"regulus/formation": "1.5.*"
},

然后在命令行中运行 php composer.phar update。Composer将安装Formation包。现在,你只需在 config/app.php 中注册服务提供者并设置Formation的别名即可。将以下内容添加到 providers 数组

Regulus\Formation\FormationServiceProvider::class,

并将以下内容添加到 aliases 数组

'Form' => Regulus\Formation\Facade::class,

你可以使用 'Formation' 或其他别名,但为了简便起见,建议使用 'Form'。Formation现在可以使用了。

现在,从命令行发布配置文件 form.php 以及视图和JS文件

php artisan vendor:publish

1. 表单构建器

表单构建器的以下是一些精选特性:- 填充表单数据(包括默认值和由POST数组提供的数据)- 在标签和表单字段中添加 error 类- 根据字段名称添加ID到表单字段,并为字段的标签添加匹配的 for 属性- 提供了验证POST数组中特定数组以及整个表单的能力- 默认使用Twitter Bootstrap 4类设置表单元素,但可以轻松地定制其他CSS框架- 允许使用PHP和JS的组合来自动创建Handlebars JS表单模板

所有这些都可以用很少的代码实现

{!! Form::field('first_name') !!}

{!! Form::field('password') !!}

{!! Form::field('user.item', 'select', [
	'options' => prep_options(Item::all(), ['id', 'name'])
]) !!}

简单地回显 Form::field('first_name') 等同于以下代码

<div class="form-group" id="field-first-name-area">
	{!! Form::label('first_name') !!}

	{!! Form::text('first_name') !!}

	{!! Form::error('first_name') !!}
</div>

上述代码可能产生以下标记

<div class="form-group has-error" id="field-first-name-area">
	<label for="field-first-name" class="control-label has-error"><span class="access">F</span>irst Name</label>

	<input type="text" name="first_name" id="field-first-name" class="form-control has-error" placeholder="First Name" accesskey="f" value="Joe" />

	<div class="error">The First Name field is required.</div>
</div>

以上代码展示了Formation如何简单且多功能。前三个字段利用了Formation简化的field()方法,中间部分展示了如何以另一种方式实现前两个文本字段的相同标记,最后部分展示了由上述两个示例可能产生的标记(假设已为“first_name”字段设置了“required”表单验证规则,并且已提交表单)。您可能注意到标记非常全面和完整。快捷键会被自动使用(除非您另有指定),并且将“access”类应用到标签的快捷键字母上。标签、字段以及可能的错误都将被包裹在具有Twitter Bootstrap“form-group”类的div标签中。ID基于名称,但使用短横线而不是下划线,标签也自动从名称创建(但也可以手动指定)。当表单数据提交到页面时,所有字段都会自动填充。字段、标签、错误、容器以及ID/类前缀的类可以在配置文件中自定义。

<input name="user[name]" value="" />
<input name="user[email]" value="" />

<input name="other_field" value="" />

使用此表单,我们可以使用Form::isValid('user')仅验证用户数组中的字段,使用Form::isValid('root')验证最后一个字段,或者使用Form::isValid()验证表单中的所有字段。

示例路由

如果您将example_routesconfig/form.php中设置为true,或者将其设置为null并设置您的APP_ENV变量在.env中为除production之外的其他任何内容,您就可以访问/formation来加载示例视图并查看Formation的实际应用。建议您同时查阅文档,以更好地了解Formation的功能及其工作原理。

打开表单

打开一个表单以POST到当前URL

{!! Form::open() !!}

使用给定的URI和请求方法打开表单

{!! Form::open(['url' => user/profile']) !!}

打开一个可以上传文件的表单

{!! Form::openForFiles(['url' => 'user/profile', 'files' => true]) !!}

打开一个资源控制器表单

{!! Form::openResource() !!}

注意:此方法自动为表单操作创建正确的路由,假设使用资源控制器。

关闭表单

{!! Form::close() !!}

默认表单值

Formation最有用的功能之一是它能够接受一个数组、对象或Eloquent模型,并使用它来自动填充表单字段。当表单被提交时,它将自动使用POST数组中的值。

$defaults = [
	'name'   => 'Ron Paul',
	'email'  => 'ron@paul.com',
	'active' => true,
];

Form::setDefaults($defaults);

注意:如果您想使用数组字段名称,请使用例如user.nameuser.email而不是nameemail

在表单POST后强制设置默认值

Form::resetDefaults();

通过关系设置默认值

$user = User::find(1);

Form::setDefaults($user, ['posts']);

这将自动设置用户在模型中定义的posts关系的默认值。

基于特定属性设置关系默认值

$user = User::find(1);

Form::setDefaults($user, [
	'posts' => '*',
	'roles' => 'id',
]);

posts项将像上面的示例一样工作(尽管这是同一事物的关联数组版本),而roles项将只选择关系中添加到默认数组的id属性。这可以用于具有roles.名称前缀的复选框集,用于管理belongsToMany()关系中的记录选择。下面复选框和单选按钮集部分有一个示例。

验证规则

Formation 使用 Laravel 的 Validator 类。使用 Form::setValidation() 会创建 Validator 类的一个实例(如果表单设置中使用数组字段名,则可能创建多个实例)。表单的验证规则通过 Formation 传递给 Validator 的原因是 Formation 在触发错误时自动将 "error" 类添加到标签和表单字段。为此,Formation 需要设置好的验证规则的一个副本。

$rules = [
	'user.name' => ['required'], // 'user.name' can be used for an array field like "user[name]"
	'email'     => ['required', 'email']
];

Form::setValidationRules($rules);

验证所有字段

if (Form::isValid())
{
	return true;
}

验证数组中的字段

if (Form::isValid('user')) // validates array fields with names like "user[name]" and "user[email]"
{
	return true;
}

if (Form::isValid('user.')) // ending with a "." allows us to validate fields like "user[0][name]" and "user[1][name]"
{
	return true;
}

以下示例可用于有多个数组字段实例的情况,如上面的 user。该示例将验证 Input::get('user') 的所有子字段。在名称后面加上句点让 Formation 知道 user 是一个可能包含多个相同子字段集合的数组。

标签

使用数组设置标签

$labels = [
	'name'  =>  'Name',
	'email' => 'Email Address',
];

Form::setLabels($labels);

通过使用数组设置您的标签,您可以在 Form::label() 中将第二个参数设置为 null

生成标签元素

{!! Form::label('email', 'Email Address') !!}

如果您不为第二个参数传递标签,它将在 Formation 的 $labels 数组中查找,该数组可以使用 Form::setLabels() 设置。如果在这里找不到,它将从第一个参数中的字段名推断出来。

指定标签的额外 HTML 属性

{!! Form::label('email', 'Email Address', ['class' => 'email']) !!}

注意:创建标签后,任何具有与标签名称匹配的名称的表单元素都将自动接收与标签名称匹配的 ID。

文本、文本区域、密码和隐藏字段

生成文本输入元素

{!! Form::text('username') !!}

指定文本输入元素的默认值

{!! Form::text('email', ['value' => 'example@gmail.com']) !!}

设置文本字段的属性

{!! Form::text('user.first_name', ['class' => 'short']) !!}

通过使用 Form::setDefaults(),您不需要传递默认值,而是可以将第二个参数传递为 null 或不传递任何值,让字段利用预设的默认值。当表单提交时,如果未使用 Form::resetDefaults(),将使用 POST 数组中的值。

注意:具有 first_name 名称属性的字段将自动赋予 first-name 的 ID。名称中的下划线始终在 ID 中替换为破折号。

为具有未指定数组索引的文本字段命名,同时保留唯一的 ID

{!! Form::text('user.(0).username') !!}

以上示例将创建一个名称为 user[][username] 且 ID 为 user-0-username 的文本字段。如果您希望显式指定名称的索引,只需省略圆括号即可。

{!! Form::text('user.0.username') !!}

生成密码输入元素

{!! Form::password('password') !!}

复选框和单选按钮

生成复选框输入元素

{!! Form::checkbox('name', ['value' => 'X']) !!}

生成带标签的复选框输入元素

{!! Form::checkbox('name', ['label' => true]) !!}

{!! Form::checkbox('name', ['label' => 'Custom Label']) !!}

{!! Form::checkbox('name', ['label' => 'Custom Label', 'label-first' => true]) !!}

生成默认勾选的复选框

{!! Form::checkbox('name', ['checked' => true]) !!}

请注意,如果使用 Form::setDefaults() 设置了默认值,您将不需要第二个参数来设置值。

注意:单选按钮方法与复选框方法的签名相同。一举两得!

复选框和单选按钮组

创建一组复选框

<?php $checkboxes = simple_options(['Rain', 'Thunder', 'Lightning']); ?>
{!! Form::checkboxSet($checkboxes) !!}

为每个复选框的名称添加前缀

{!! Form::checkboxSet($checkboxes, ['name-prefix' => 'weather']) !!}

在此示例中,复选框的名称属性都将为 weather[]

使用显式键为每个复选框的名称添加前缀

{!! Form::checkboxSet($checkboxes, ['name-prefix' => 'weather', 'explicit-keys' => true]) !!}

{!! Form::checkboxSet($checkboxes, ['name-prefix' => 'weather.']) !!}

这两个示例都将产生类似 weather[Thunder] 的名称属性。在末尾包含一个 . 字符会自动使用显式键,但您也可以将其作为属性传递,以便更容易理解正在发生的情况。

强制将复选框选项解释为关联数组

{!! Form::checkboxSet($checkboxes, ['associative' => true]) !!}

默认情况下,checkboxSet() 将您的数组解释为关联数组,除非键是整数或键是等于正整数的字符串,但您可以通过传递一个 associative 布尔值来强制它以任何一种方式解释复选框选项。

指定用作复选框值的对象

<?php $checkboxes = [
	'checkbox_name'  => 'Checkbox Label!',
	'checkbox_name2' => 'Checkbox Label 2!',
]; ?>
{!! Form::checkboxSet($checkboxes, ['name-values' => true]) !!}

{!! Form::checkboxSet($checkboxes, ['label-values' => true]) !!}

默认情况下,复选框的值简单地是 1,但您可以将复选框集设置为使用名称作为值(关联数组的键)或标签作为值(关联数组的值)。

管理多对一关系中的选择

$user = App\Models\User\User::find(1);

Form::setDefaults($user, [
	'roles' => 'id',
]);

$roleOptions = prep_options(App\Models\User\Role::get(), ['id', 'name']);
{!! Form::checkboxSet($roleOptions, [
	'name-prefix' => 'roles',
	'associative' => true,
	'name-values' => true,
]) !!}

为复选框和/或无序列表容器添加属性

{!! Form::checkboxSet($checkboxes, [
	'class'        => 'weather',
	'id-container' => 'checkbox-set-weather',
]) !!}

注意:以 "-container" 结尾的属性将添加到容器本身,而不是每个复选框。

创建一组单选按钮

{!! Form::radioSet('weather', simple_options(['Rain', 'Thunder', 'Lightning'])) !!}

注意:在上述示例中,simple_options() 方法仅用于将单选按钮的标签也用作实际表单字段的值,而不是使用数组项的数字索引。有关构建选项的更多方法,请参阅文档中即将到来的 下拉列表 部分。

您可以将 "-container" 添加到属性名称,以便将其分配给单选按钮集的容器元素。单选按钮和复选框的默认容器类是 radio-setcheckbox-set。容器是无序列表元素,集合中的每个项目都是列表中的一个列表项。

下拉列表

从项目数组生成下拉列表

{!! Form::select('size', ['L' => 'Large', 'S' => 'Small']) !!}

使用具有空值的标签作为列表中的第一个选项

{!! Form::select('size', ['L' => 'Large', 'S' => 'Small'], ['null-option' => Select a Size']) !!}

生成具有默认选中选项的下拉列表

<?php // you may pass either a "selected" or "value" attribute to select an option ?>
{!! Form::select('size', ['L' => 'Large', 'S' => 'Small'], ['null-option' => 'Select a Size', 'value' => 'S']) !!}

{!! Form::select('size', ['L' => 'Large', 'S' => 'Small'], ['null-option' => 'Select a Size', 'selected' => 'S']) !!}

当然,您可以使用 Form::setDefaults() 来填充选择框,而无需第三个 selectedvalue 属性。

将数组、对象或 Eloquent 集合转换为选项集

$users = DB::table('users')->orderBy('username')->get();
{!! Form::select('user', prep_options($users, ['id', 'username']), 'Select a User') !!}

将简单数组转换为具有与标签相同值的选项数组

{!! Form::select('animal', simple_options(['Tiger', 'Zebra', 'Elephant']), ['null-option' => Select an Animal']) !!}

将简单数组转换为具有与标签相同值(除了小写)的选项数组

{!! Form::select('animal', simple_options(['Tiger', 'Zebra', 'Elephant'], true), ['null-option' => Select an Animal']) !!}

将简单数组转换为具有从一开始的数值的简单选项数组

{!! Form::select('animal', offset_options(['Tiger', 'Zebra', 'Elephant']), ['null-option' => Select an Animal']) !!}

将简单数组转换为具有从一开始的数值的简单选项数组

<?php // display options from 0 to 180 incrementing by 10 each time ?>
{!! Form::select('number', number_options(0, 180, 10)) !!}

第一个参数是起始数字,第二个参数是结束数字,第三个参数是迭代的数字。如果是负数,您可以向下计数而不是向上计数。最后,第四个参数用于表示数字应该有多少位小数。

创建月份的选项数组

<?php // count up 12 months from current month ?>
{!! Form::select('month', month_options('current', 12)) !!}
<?php // count down 12 months from current month ?>
{!! Form::select('month', month_options(true, -12)) !!}
<?php // count up to a specific month from current month ?>
{!! Form::select('month', month_options(true, '2013-04-08')) !!}
<?php // count down to a specific month from another specific month ?>
{!! Form::select('month', month_options('2013-11-11', '2013-04-08')) !!}
<?php // count down 12 months from current month and use the last day of the month for "month_end" field ?>
{!! Form::select('month_start', month_options(true, -12, false, 'M Y')) !!}
{!! Form::select('month_end', month_options(true, -12, true, 'M Y')) !!}

第一个参数是您的起始月份。您可以使用 truefalsenull 或 "current" 来使用当前月份。第二个参数可以是正数或负数,用于向上或向下计数特定数量的月份,也可以是日期字符串,用于向上或向下计数月份直到特定日期。如果第三个参数 endDate 设置为 true,则用于选项值的日期将使用月份的最后一天而不是第一天。最后,您可以为选项标签指定日期格式作为第四个参数。默认为 "F Y"。

注意:上述所有选项数组构建函数也可以用于复选框集和单选按钮集,并且是包装核心 Formation 函数的辅助函数。例如,prep_options() 使用 Form::prepOptions()

为单选按钮集使用字段宏

<?php $options = simple_options(['T-Rex', 'Parasaurolophus', 'Triceratops']); ?>
{!! Form::field('dinosaur', 'radio-set', ['label' => 'Favorite Dinosaur', 'options' => $options]) !!}

文件输入

生成文件输入元素

{!! Form::file('image') !!}

按钮

生成提交按钮元素

{!! Form::submit('Click Me!') !!}

如果未设置第一个参数,则将使用“提交”作为标签。

注意:需要创建按钮元素?尝试使用按钮方法。它具有与提交相同的签名。

字段方法

您可以使用内置的 Form::field() 方法将此转换为

<div class="form-group" id="user-email-area">
	{!! Form::label('user.email') !!}

	{!! Form::text('user.email') !!}

	{!! Form::error('user.email') !!}
</div>

转换为这样

{!! Form::field('user.email') !!}

字段容器元素可以更改为其他HTML元素,并在 config.php 中更改“form-group”类。如果您根本不想使用字段容器,可以使用以下方法

{!! Form::field('name', 'text', ['field-container' => false]) !!}

使用字段方法为下拉选择框

{!! Form::field('animal', 'select', [
	'options' => simple_options(['Tiger', 'Zebra', 'Elephant'])
]) !!}

使用字段方法为一组单选按钮

<?php $options = simple_options(['T-Rex', 'Parasaurolophus', 'Triceratops']); ?>
{!! Form::field('dinosaur', 'radio-set', ['label' => 'Favorite Dinosaur', 'options' => $options]) !!}

使用字段方法为一组复选框

{!! Form::field('number.', 'checkbox-set', [
	'options' => offset_options(['One', 'II', '3.0'])
]) !!}

您会注意到第三个参数,attributes,包含一些特殊属性选项,例如 labeloptions,这些属性与任何其他属性声明都不一样。将这些组合到属性数组中是因为字段方法的通用性和多用途性。这避免了简单字段需要大量的 null 参数。除了 labeloptions,您还可以使用 null-option 为选择框添加前置 null 选项。最后,可以使用 value 手动设置字段的值。如果您使用 setDefaults()setup 方法预填充表单数据,则此操作是不必要的。

$attributes = [
	'class'       => 'select-number',
	'options'     => number_options(1, 10),
	'null-option' => 'Select a Number',
	'value'       => 3,
];
{!! Form::field('number', 'select', $attributes) !!}

注意:以“-container”结尾的属性将添加到容器本身,而不是字段。以“-label”结尾的属性将添加到字段的标签。

2. 数据转换器基本模型 & 扩展特质

Formation 包含一个基本模型,该模型简单地扩展了 Eloquent Model 类,并使用一个包含许多高级模型功能的特质,特别是在通过 API 提供数据或在对数据库保存数据之前格式化数据方面。您可以直接从您的模型(Regulus\Formation\Models\Base)扩展 Base 模型,或者只需在现有模型中使用 Extended 特质(Regulus\Formation\Traits\Extended)。

包含在数组中的方法和属性集

包含在数组中的方法

您可以在模型中添加一个 protected static $arrayIncludedMethods 数组来指定您希望在模型通过 toArray()toJson() 运行时包含的方法。当使用前端 JS 框架(如 Vue)时,这非常有用。Laravel 的 Eloquent 模型系统已经包含用于此目的的 appends 数组,但这是一种更灵活的方法,因为它允许您传递参数并将字段重命名为您想要的名称。

protected static $arrayIncludedMethods = [
	'name' => 'getName(true)',
	'url'  => 'getUrl', // parameters not required
];

属性集

您可以在模型中添加一个 protected static $attributeSets 数组来定义特定的属性集,使用 toArray()toJson() 返回,可以使用 getAttributeSet() 和集的名称(您的数组中的键)来获取。这允许您为不同的目的定义不同的属性集。您还可以在相关内容中引用集。以下是一个完整的示例。假设我们有一个名为 Post 的模型,它通过 author() 关系属于 User,并且模型具有以下属性集

	/**
	 * The attribute sets for the model.
	 *
	 * @var array
	 */
	protected static $attributeSets = [
		'standard' => [
			'id',
			'content',
			'url', // this could even be a key listed in $arrayIncludedMethods for a getUrl() method
		],

		'update' => [
			'set:standard', // include all attributes in "standard" set
			'attribute:content', // set "content" attribute to ignore array-included method in favour of actual value from DB
		],
	];

	/**
	 * The attribute sets for related models.
	 *
	 * @var array
	 */
	protected static $relatedAttributeSets = [
		'standard' => [
			'author'  => 'set:author', // this will use an attribute set from the model used for the "author" relationship
			'section' => 'class:'.Section::class, // this will look for an attribute set called "standard"
			'tags'    => 'class:'.Tag::class.';set', // this will look for an attribute set called "set"
		],
	];

在我们的用户模型中,我们定义了以下包含在数组中的方法和属性集

	/**
	 * The methods to automatically include in a model's array / JSON object.
	 *
	 * @var array
	 */
	protected static $attributeSets = [
		'author' => [
			'id',
			'username',
			'select:first_name', // this data is only being selected, and will be combined using the "getName" method defined above
			'select:last_name', // this data is only being selected, and will be combined using the "getName" method defined above
			'name',
		],
	];

	/**
	 * The attribute sets for the model.
	 *
	 * @var array
	 */
	protected static $arrayIncludedMethods = [
		'name' => 'getName',
	];

注意:如果您直接使用扩展特性行为而不是扩展基础模型,那么您需要将所有变换配置放置在单个名为 $transformConfig 的静态数组中,因为您不能覆盖特性行为的静态变量(此格式也适用于扩展基础模型,但在此情况下不是必需的)

	/**
	 * The data transforming configuration.
	 *
	 * @var array
	 */
	public static $transformConfig = [
		'arrayIncludedMethods' => [
			//
		],

		'attributeSets' => [
			'standard' => [
				//
			],
		],

		'relatedAttributeSets' => [
			'standard' => [
				//
			],
		],
	];

现在,我们可以使用 author 关系查询 Post 模型,并以 JSON 数据的形式返回它

	$post = Post::selectAttributeSet('standard')
		->limitRelatedData()
		->first();

	// selectSet is short-hand alias for selectAttributeSet
	$users = User::selectSet('author', true), passing true as the second parameter automatically calls limitRelatedData() scope
		->get()
		->toArray();

我们上面的例子实际上不需要 standard 参数,因为它们是各自函数的默认值。 selectAttributeSet() / selectSet() 使用 getAttributeSet(),但默认情况下也使用 "select" 属性集键(如果 "select" 不可用,则回退到 "standard"),并在可能的情况下添加表前缀(如果您使用具有模糊列名的 JOIN)。它还删除了用于表示要选择但不返回到数组中的字段的 select: 前缀(对于使用数组包含方法的底层列的情况)。如果您有一个与使用数组包含方法的动态属性同名的属性,您可以在属性集中添加一个 attribute: 前缀,以便在 toArray() 中使用原生属性而不是动态创建的属性。

这将使我们能够大幅减少返回的数据量,从而仅获取所需的数据而无需更多

注意:如果您使用 selectAttributeSet() / selectSet()limitRelatedData() 范围,对模型实例、集合或分页器调用 toLimitedArray() 将使用之前提供的任何属性集。

	{
		"id":343,
		"content":"Taxation is theft, purely and simply even though it is theft on a grand and colossal scale which no acknowledged criminals could hope to match. It is a compulsory seizure of the property of the State's inhabitants, or subjects.",
		"created_at":"1973-03-02 00:00:00",
		"author":{
			"id":1,
			"username":"ForANewLiberty",
			"name":"Murray Rothbard"
		}
	}

您还可以在 toArray() 方法中指定属性集,或使用 toLimitedArray(),它将 standard 作为第一个参数自动选择标准属性集

	return $post->toArray('standard');

	return $post->toLimitedArray(); // same as above, assumes "standard" by default

	return Post::orderBy('id')->get()->toArray('standard'); // filter models in a collection with attribute set

最后,Record::getAttributeSet('fillable') 将返回 "id" 属性以及模型 $fillable 数组中列出的任何内容。

将分页器转换为数组

Extended 特性行为使用了 Formation 对 Laravel 相关模型类的所有扩展。这意味着 toArray()toLimitedArray() 都可用于模型实例、模型集合以及由模型的 paginate() 方法创建的分页器。

	return Post::orderBy('id')->paginate(25)->toArray('standard'); // return a paginator converted to an array

	return Post::orderBy('id')->setPage(3)->paginate(25)->collectionToArray('standard'); // return just the collection

注意: toLimitedArray()collectionToLimitedArray() 也可用于将属性集默认为 "standard"。

为保存到数据库格式化数据

类型

您可以在模型中添加一个 protected static $types 数组,以便在将数据用于填充表单或保存到数据库之前自动格式化数据。以下类型可以使用

  • 复选框
  • 日期
  • 日期时间
  • 日期时间
  • 时间戳
  • 非空日期
  • 非空日期时间
  • 非空日期时间
  • 非空时间戳
  • 令牌(仅在记录创建时设置,默认长度为 32,但可以设置自定义长度,例如 token:16
  • 别名
  • 唯一别名
  • 复选框时间戳(如果字段是 active,则保存的时间戳变为 active_at,但您也可以指定自定义字段,例如 checkbox-timestamp:activated_at

注意:您可以参考 Regulus\Formation\Traits\Extended 特性行为以获取此示例和其他所有辅助数组的示例。特性行为包含针对它们的每个数组的注释掉的数组示例。

格式

您可以在模型中添加 protected static $formatsprotected static $formatsForDb 数组,以便在填充表单或保存数据之前进行一些额外的自动数据格式化。

	/**
	 * The special formatted fields for the model for saving to the database.
	 *
	 * @var array
	 */
	protected static $formatsForDb = [
		'media_type'   => 'null-if-false:media',
		'published_at' => 'null-if-false:published',
	];

以下格式可以使用

  • 如果为空则返回false
  • 如果为空则返回true
  • 如果不为空则返回false
  • 如果不为空则返回true
  • 如果为空则返回false
  • 如果为空则返回true
  • 如果为空则返回null
  • 如果不为空则返回false
  • 如果不为空则返回true
  • 如果不为空则返回null
  • 如果已设置则返回false
  • 如果为真则返回false
  • 如果已设置则返回true
  • 如果为真则返回false
  • 如果已设置则返回null
  • 如果为真则返回null
  • 如果没有设置则返回false
  • 如果为假则返回false
  • 如果没有设置则返回true
  • 如果为假则返回true
  • 如果没有设置则返回null
  • 如果为假则返回null
  • JSON
  • JSON或null
  • 去除前后空格
  • 首字母大写
  • 单词首字母大写
  • 全部大写
  • 全部小写

在保存到数据库之前,将使用 $types$formats$formatsForDb 的格式进行自动格式化,当使用 formatSave()formatCreate() 方法时。您也可以通过使用模型或特质的自己的 setDefaults() 方法来运行它们。或者,您可以使用 getFormattedValues() 来获取格式化值的数组。许多格式选项,如 如果没有设置则返回null,将允许您在要检查的字段不是应用格式化规则的字段时传递已检查的字段。例如,如果您有一个名为 location_info 的字段,您可以将 如果没有设置则返回null:location 设置,如果POST数据中没有设置 location 布尔值,则 location_info 将被更改为 null

格式化与保存数据

设置完上述格式后,您可以使用 $record->formatSave()Record::formatCreate() 自动格式化数据并保存。如果您在模型中设置了 formatValuesForModel() 方法,您可以在 $types$formats$formatsForDb 数组中添加自定义格式化规则。此外,您可以在 executeSaveTriggers($create = false) 方法中添加额外的保存后逻辑(用于在关系或需要记录首先存在的情况下执行其他操作)。

验证

您始终可以使用 Form::setValidationRules($rules, $input),但如果您使用基本模型或特质,您可以在模型中定义一个 validationRules($record = null, $input = null, $action = null) 函数之后执行以下任何操作。建议您从扩展特质中复制一个空白的作为起点使用。默认情况下,第三个参数 $action 不使用,但存在以提供根据不同的数据更新操作设置不同验证规则的能力。如果您在模型中设置了该方法,您可以使用以下任何一种方法来设置验证规则

// new record
Form::setValidationRulesForNew($input);

// existing record
$record->setValidationRules($input);

// new or existing record ($record can be null)
Form::setValidationRulesForModel($record, $input);

注意:如果您想使用所有输入值,则不需要传递 $input,它将默认为 Input::all()