Yii - Creating a Behavior



Assume we want to create a behavior that will uppercase the “name” property of the component the behavior is attached to.

Step 1 − Inside the components folder, create a file called UppercaseBehavior.php with the following code.

<?php
   namespace app\components;
   use yii\base\Behavior;
   use yii\db\ActiveRecord;
   class UppercaseBehavior extends Behavior {
      public function events() {
         return [
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
         ];
      }
      public function beforeValidate($event) {
         $this->owner->name = strtoupper($this->owner->name);
     }
   }
?>

In the above code we create the UppercaseBehavior, which uppercase the name property when the “beforeValidate” event is triggered.

Step 2 − To attach this behavior to the MyUser model, modify it this way.

<?php
   namespace app\models;
   use app\components\UppercaseBehavior;
   use Yii;
   /**
   * This is the model class for table "user".
   *
   * @property integer $id
   * @property string $name
   * @property string $email
   */
   class MyUser extends \yii\db\ActiveRecord {
      public function behaviors() {
         return [
            // anonymous behavior, behavior class name only
            UppercaseBehavior::className(),
         ];
      }
      /**
      * @inheritdoc
      */
      public static function tableName() {
         return 'user';
      }
      /**
      * @inheritdoc
      */
      public function rules() {
         return [
            [['name', 'email'], 'string', 'max' => 255]
         ];
      }
      /**
      * @inheritdoc
      */
      public function attributeLabels() {
         return [
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'Email',
         ];
      }
   }
?>

Now, whenever we create or update a user, its name property will be in uppercase.

Step 3 − Add an actionTestBehavior function to the SiteController.

public function actionTestBehavior() {
   //creating a new user
   $model = new MyUser();
   $model->name = "John";
   $model->email = "john@gmail.com";
   if($model->save()){
      var_dump(MyUser::find()->asArray()->all());
   }
}

Step 4 − Type http://localhost:8080/index.php?r=site/test-behavior in the address bar you will see that the name property of your newly created MyUser model is in uppercase.

UppercaseBehavior
Advertisements