I have a form with multi-select fields named "city" form in Yii2. When I submit form the post data show me the following:
$_POST['city'] = array('0'=>'City A','1'=>'City B','2'=>'City C')
But I want to save the array in serialize form like:
a:3:{i:0;s:6:"City A";i:1;s:6:"City B";i:2;s:6:"City C";}
But I don't know how to modify data before save function in Yii2. Followin is my code:
if(Yii::$app->request->post()){
$_POST['Adpackage']['Page'] = serialize($_POST['Adpackage']['Page']);
$_POST['Adpackage']['fixer_type'] = serialize($_POST['Adpackage']['fixer_type']);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model
]);
}
Please help me.
Thanks all for your effort. I have solved the issue. here is the code :
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$this->Page = serialize($_POST['Adpackage']['Page']);
$this->fixer_type = serialize($_POST['Adpackage']['fixer_type']);
return true;
} else {
return false;
}
}
Just put this code in model and its working
It's because Yii::$app->request->post()
is different than $_POST
at this stage. Try to change your code to:
$post = Yii::$app->request->post();
$post['Adpackage']['Page'] = serialize($post['Adpackage']['Page']);
$post['Adpackage']['fixer_type'] = serialize($post['Adpackage']['fixer_type']);
$model->load($post);
Update:
Also it would be better to do it on ActiveRecord beforeSave()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With