Yii2 框架。为通用模型创建通用行为的想法:
如果是数组,则修剪数组中的所有值。
我想知道为什么在 Yii2 core 中不存在这种可能性。或者我错了。我是吗
如果修剪所有字段,我会遇到什么问题?
您可以创建一个行为并将其附加到您的模型上。
1) 在
TrimBehavior
中创建行为 common/components
。
<?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)在您的模型中添加以下内容:
//...
use common\components\TrimBehavior;
//...
/**
* Returns a list of behaviors that this component should behave as.
*
* @return array
*/
public function behaviors()
{
return [
[
'class' => TrimBehavior::className(),
],
];
}
修剪属性取决于业务逻辑。如果你真的需要的话那就没问题了
我尝试了 Kostas Mitsarakis 使用行为建议的解决方案,发现虽然它有效,但会产生一些额外的问题。我认为应该在
trim
数据上执行 $_POST
操作,因此将此函数添加到您的控制器中,所有发布的数据将在进入模型之前被修剪:
public function beforeAction($action)
{
array_walk_recursive($_POST, function (&$val, $index)
{
$val = trim($val);
// maybe also:
// if(empty($val)) $val = null;
});
return parent::beforeAction($action);
}