【问题标题】:Yii2 populate update form with values stored in arrayYii2 使用存储在数组中的值填充更新表单
【发布时间】:2015-05-08 23:36:22
【问题描述】:

我创建了一个包含以下字段的表单,并在保存到单个数据库字段之前使用了 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,
        ]);
    }
}

【问题讨论】:

  • 你能展示一下你是怎么做 json_encode 的吗?是在控制器还是模型中?
  • public function actionCreate() { $model = new Article(); $model-&gt;user_id = Yii::$app-&gt;user-&gt;id; if ($model-&gt;load(Yii::$app-&gt;request-&gt;post())) { $seo_information = $_POST['Article']['seo_information']; $model-&gt;seo_information = json_encode($seo_information); $model-&gt;save(); return $this-&gt;redirect(['view', 'id' =&gt; $model-&gt;id]); } else { return $this-&gt;render('create', [ 'model' =&gt; $model, ]); } } 可以做一些验证。
  • 哦...请把它放到你的问题中!请编辑问题并插入代码。

标签: php activerecord model-view-controller yii2


【解决方案1】:

应该这样做:

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

如果 db 中的值为 NULL,这也有效。

【讨论】:

    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多