Yii2 trim everything on save

浪尽此生 提交于 2019-12-06 05:12:10

问题


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.

    1. I'm wondered why in Yii2 core doesn't exist such possibility. Or I'm wrong. Am I?

    2. What problems could I face if I trim all fields?


回答1:


You can create a behavior and attach it at your models.

1) Create the behavior TrimBehavior in 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) 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.



来源:https://stackoverflow.com/questions/36745747/yii2-trim-everything-on-save

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!