簡體   English   中英

Yii2使用存儲在數組中的值填充更新表單

[英]Yii2 populate update form with values stored in array

我創建了具有以下字段的表單,並在保存到單個數據庫字段之前使用json編碼。

現在,當使用更新表單時,我需要填充字段,但是我不確定,因為我找不到任何yii2示例。

<?= $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') ?>

控制器創建代碼

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,
        ]);
    }
}

應該這樣做:

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

如果db中的值為NULL,這也將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM