简体   繁体   中英

before save in Yii2

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM