Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before save in Yii2

Tags:

php

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

like image 408
Rajinder Avatar asked Jun 18 '15 11:06

Rajinder


1 Answers

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.

like image 145
Patryk Radziszewski Avatar answered Oct 02 '22 00:10

Patryk Radziszewski