我创建了一个包含以下字段的表单,并在保存到单个数据库字段之前使用 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') ?>
Controller 创建代码
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,
]);
}
如果数据库中的值为 NULL,这也适用。
关于php - Yii2 使用存储在数组中的值填充更新表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134343/