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.
trim
rule, yiiframework.com/doc-2.0/… – Resolutive