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
.
1) Create the behavior TrimBehavior
in common/components
.
<?php
namespace commoncomponents;
use yiidbActiveRecord;
use yiiaseBehavior;
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 commoncomponentsTrimBehavior;
//...
/**
* 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屋!
查看全文