This behavior is very useful in case of usage of ActiveRecord for the schema-less databases like MongoDB or Redis. It may also come in handy for regular ActiveRecord or even Model, allowing to maintain strict attribute types after model validation. This behavior should be attached to Model or BaseActiveRecord descendant. You should specify exact attribute types via [[attributeTypes]]. For example: php use yii\behaviors\AttributeTypecastBehavior; class Item extends \yii\db\ActiveRecord { public function behaviors() { return [ 'typecast' => [ 'class' => AttributeTypecastBehavior::className(), 'attributeTypes' => [ 'amount' => AttributeTypecastBehavior::TYPE_INTEGER, 'price' => AttributeTypecastBehavior::TYPE_FLOAT, 'is_active' => AttributeTypecastBehavior::TYPE_BOOLEAN, ], 'typecastAfterValidate' => true, 'typecastBeforeSave' => false, 'typecastAfterFind' => false, ], ]; } ... } Tip: you may left [[attributeTypes]] blank - in this case its value will be detected automatically based on owner validation rules. Following example will automatically create same [[attributeTypes]] value as it was configured at the above one: php use yii\behaviors\AttributeTypecastBehavior; class Item extends \yii\db\ActiveRecord { public function rules() { return [ ['amount', 'integer'], ['price', 'number'], ['is_active', 'boolean'], ]; } public function behaviors() { return [ 'typecast' => [ 'class' => AttributeTypecastBehavior::className(), 'attributeTypes' will be composed automatically according to rules() ], ]; } ... } This behavior allows automatic attribute typecasting at following cases: - after successful model validation - before model save (insert or update) - after model find (found by query or refreshed) You may control automatic typecasting for particular case using fields [[typecastAfterValidate]], [[typecastBeforeSave]] and [[typecastAfterFind]]. By default typecasting will be performed only after model validation. Note: you can manually trigger attribute typecasting anytime invoking AttributeTypecastBehavior::typecastAttributes method: php $model = new Item(); $model->price = '38.5'; $model->is_active = 1; $model->typecastAttributes();
Since: 2.0.10
Author: Paul Klimov (klimov.paul@gmail.com)
Inheritance: extends yii\base\Behavior
 /**
  * @inheritdoc
  */
 public function attach($owner)
 {
     parent::attach($owner);
     if ($this->attributeTypes === null) {
         $this->reinitAutoDetectedAttributeTypes();
     }
 }