01/10
2015
Wallogit.com
2017 © Pedro Peláez
Behavior that convert array to JSON before save data in model
Behavior that convert array to JSON before save data in model, (*1)
Install via composer, (*2)
composer require emidia/yii2-jsonify
Or you may add dependency manually in composer.json:, (*3)
"emidia/yii2-jsonify": "*"
To use JsonifyBehavior, insert the following code to your ActiveRecord class:, (*4)
use emidia\yii2\JsonifyBehavior;
public function behaviors()
{
return [
JsonifyBehavior::className(),
];
}
By default JsonifyBehavior fill json_data attribute from array into a json encoded string, (*5)
If your attribute names are different, you may configure the [[attribute]] properties like the following:, (*6)
public function behaviors()
{
return [
[
'class' => JsonifyBehavior::className(),
'attribute' => 'data',
],
];
}
So, if set an array in model's attribute, this behavior will convert all data to JSON, (*7)
$model->setAttributes([
'data' => [
'id'=> 12,
'title' => 'test'
]
]);