Yii Tutorial on 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