2

I have created a form with the following fields and use json encode before saving to a single database field.

Now I need to populate the fields when using the update form however I am unsure as i can't find any yii2 example.

<?= $form->field( $model, 'seo_information[field1]' )
          ->textInput( [ 'maxlength' => 255 ] )
          ->label('Array Field 1) ?>

<?= $form->field( $model, 'seo_information[field2]' )
         ->textInput( [ 'maxlength' => 255 ] )
         ->label('Array Field 2') ?>

<?= $form->field( $model, 'seo_information[field3]' )
         ->textInput( [ 'maxlength' => 255 ] )
         ->label('Array Field 3') ?>

Controller Create Code

public function actionCreate()
{
    $model = new Article();
    $model->user_id = Yii::$app->user->id;

    if ($model->load(Yii::$app->request->post())) 
    {
        $seo_information = $_POST['Article']['seo_information'];
        $model->seo_information = json_encode($seo_information); 
        $model->save();
        return $this->redirect(['view', 'id' => $model->id]);
    } 
    else 
    {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
3
  • 1
    Could you show how you do json_encode? Is it in controller or model? Commented May 10, 2015 at 9:41
  • public function actionCreate() { $model = new Article(); $model->user_id = Yii::$app->user->id; if ($model->load(Yii::$app->request->post())) { $seo_information = $_POST['Article']['seo_information']; $model->seo_information = json_encode($seo_information); $model->save(); return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } Could do with some validation. Commented May 10, 2015 at 11:58
  • 1
    Oh... please put that into your question! Just edit the question and insert the code, please. Commented May 10, 2015 at 12:06

1 Answer 1

2

This should do it:

else 
{
     $model->seo_information = json_decode($model->seo_information, true); 
     return $this->render('create', [
         'model' => $model,
     ]); 
}

This works also if the value in the db is NULL.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.