简体   繁体   English

在Yii2中保存之前

[英]before save in Yii2

I have a form with multi-select fields named "city" form in Yii2. 我有一个表格,在Yii2中有一个名为“city”形式的多选字段。 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. 但我不知道如何在Yii2中保存功能之前修改数据。 Followin is my code: Followin是我的代码:

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. 这是因为在这个阶段Yii::$app->request->post()$_POST不同。 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. 最好在ActiveRecord beforeSave()方法上执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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