Before saving to Yii2

I have a form with fields with several fields named "city" in Yii2. When I submit the form, the message data shows me the following:

$_POST['city'] = array('0'=>'City A','1'=>'City B','2'=>'City C') 

But I want to save the array in serialization form, for example:

 a:3:{i:0;s:6:"City A";i:1;s:6:"City B";i:2;s:6:"City C";} 

But I do not know how to change the data before the 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.

Thank you all for your efforts. I solved the problem. 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 the model and its working

+7
php yii2
source share
1 answer

This is because Yii::$app->request->post() is different from $_POST at this point. Try changing 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:

It would also be better to do this using the ActiveRecord method beforeSave() .

+2
source share

All Articles