Yii2修剪一切保存

Ale*_*nko 4 behavior trim yii2

Yii2框架.为共同模型创建共同行为的想法:

  • 在验证之前修剪模型中的所有字段.
  • 如果它的数组修剪数组中的所有值.

    1. 我想知道为什么在Yii2核心中不存在这种可能性.或者我错了.我呢?

    2. 如果修剪所有字段,我可能遇到什么问题?

Kos*_*kis 9

您可以创建行为并将其附加到模型中.

1)创建行为TrimBehaviorcommon/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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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(),
        ],
    ];
}
Run Code Online (Sandbox Code Playgroud)

修剪属性取决于业务逻辑.如果你真的需要它,那就没关系.

  • 您必须根据每次需要使用 is_array() 或其他方法进行检查。 (2认同)