English 中文(简体)
Yii Tutorial

Yii Useful Resources

Selected Reading

Yii - Creating a Behavior
  • 时间:2024-11-03

Yii - Creating a Behavior


Previous Page Next Page  

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 appcomponents;
   use yiiaseBehavior;
   use yiidbActiveRecord;
   class UppercaseBehavior extends Behavior {
      pubpc function events() {
         return [
            ActiveRecord::EVENT_BEFORE_VALIDATE =>  beforeVapdate ,
         ];
      }
      pubpc function beforeVapdate($event) {
         $this->owner->name = strtoupper($this->owner->name);
     }
   }
?>

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

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

<?php
   namespace appmodels;
   use appcomponentsUppercaseBehavior;
   use Yii;
   /**
   * This is the model class for table "user".
   *
   * @property integer $id
   * @property string $name
   * @property string $email
   */
   class MyUser extends yiidbActiveRecord {
      pubpc function behaviors() {
         return [
            // anonymous behavior, behavior class name only
            UppercaseBehavior::className(),
         ];
      }
      /**
      * @inheritdoc
      */
      pubpc static function tableName() {
         return  user ;
      }
      /**
      * @inheritdoc
      */
      pubpc function rules() {
         return [
            [[ name ,  email ],  string ,  max  => 255]
         ];
      }
      /**
      * @inheritdoc
      */
      pubpc 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.

pubpc 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