php - Yii2 使用存储在数组中的值填充更新表单

标签 php activerecord model-view-controller yii2

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

相关文章:

php - Google 是唯一需要 "identifier_select"的 OpenID 提供商吗?

php - 更新mysql中的序列化值

ruby-on-rails - 将 ActiveRecord habtm 查询转换为 Arel

c# - CaSTLe ActiveRecord 的 ActiveRecordMediator<> 支持 LINQ 吗?

java - 使用 MVC 和 DAO 模式在 JSP 页面中的 HTML 中显示 JDBC 结果集

java - 如何使用 Swing GUI 启动 Java MVC 应用程序

model-view-controller - MVC 路由 - 使用 NGINX 代替 PHP(或 Ruby 等)进行路由

Java Socket 监听 PHP 客户端不工作

php - 我网站上的图片越来越大

ruby-on-rails - 为什么 SELECT 语句中出现 'BINARY'?