Yii2在保存时修剪所有内容 [英] Yii2 trim everything on save
本文介绍了Yii2在保存时修剪所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Yii2框架.为通用模型创建通用行为的想法:
Yii2 framework. The idea to create common behavior for common model:
- 在验证"之前修剪模型中的所有字段.
-
如果是数组,则修剪数组中的所有值.
- before Validate trims all fields in model.
if it's array trim all values in array.
-
我想知道为什么在Yii2核心中不存在这种可能性.还是我错了.我是吗?
I'm wondered why in Yii2 core doesn't exist such possibility. Or I'm wrong. Am I?
如果我修剪所有字段会遇到什么问题?
What problems could I face if I trim all fields?
推荐答案
您可以创建行为并将其附加到模型中.
You can create a behavior and attach it at your models.
1)在 common/components
中创建行为 TrimBehavior
.
<?php
namespace common\components;
use yii\db\ActiveRecord;
use yii\base\Behavior;
class TrimBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
];
}
public function beforeValidate($event)
{
$attributes = $this->owner->attributes;
foreach($attributes as $key => $value) { //For all model attributes
$this->owner->$key = trim($this->owner->$key);
}
}
}
2)在您的模型中添加以下内容:
2) In your models add the following:
//...
use common\components\TrimBehavior;
//...
/**
* Returns a list of behaviors that this component should behave as.
*
* @return array
*/
public function behaviors()
{
return [
[
'class' => TrimBehavior::className(),
],
];
}
整理属性取决于业务逻辑.如果您真的需要它,那没关系.
Trimming attributes it depends on business logic. If you really need it then it's ok.
这篇关于Yii2在保存时修剪所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文