php - Yii2 将表单字段数组保存到单个数据库字段

标签 php arrays yii2

如何在 Yii2 中保存字段数组,当前/默认设置仅适用于不是数组的字段。

以下是我需要保存到单个字段中的表单字段:

<div class="repeat">
<table class="wrapper" width="100%">
    <thead>
        <tr>
            <td width="10%" colspan="4"><span class="add">Add</span></td>
        </tr>
    </thead>
    <tbody class="container">
    <tr class="template row">
        <td width="10%"><span class="move">Move</span></td>

        <td width="10%">An Input Field</td>

        <td width="70%">
            <?= $form->field($model, 'field1ofarray[{{row-count-placeholder}}]')->textInput(['maxlength' => 255])->label('Field Label') ?>
            <?= $form->field($model, 'fieldofarray[{{row-count-placeholder}}]')->textInput(['maxlength' => 255])->label('Som field') ?>
            <?= $form->field($model, 'field3ofarray[{{row-count-placeholder}}]')->textInput(['maxlength' => 255])->label('Field Label') ?>
            <?= $form->field($model, 'field4ofarray[{{row-count-placeholder}}]')->dropDownList(['instock' => 'Instock', 'soldout' => 'Sold Out', 'scheduled' => 'Scheduled']); ?>
        </td>

        <td width="10%"><span class="remove">Remove</span></td>
    </tr>
    </tbody>
</table>

当前 Controller (我需要知道如何遍历数组并保存以及保存表单中的其他普通字段):

public function actionCreate()
{
    $model = new GrailWall();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

最佳答案

就我而言,我根本不需要对 Controller 进行任何更改。

您可以在您的数据库记录中创建一个字段,例如“config_json”,然后在您的模型中定义一个带有 getter 和 setter 的虚拟属性。

public function getConfig()
{
    return json_decode($this->config_json);
}

public function setConfig($value)
{
    $this->config_json = json_encode($value);
}

同时将您的虚拟属性(property)设置为安全的规则,以便 Massive Assignment 起作用。

public function rules()
{
    return [
        [['company_id', 'created_at', 'updated_at'], 'integer'],
        [['class'], 'required'],
        [['config_json'], 'string'],
        [['class'], 'string', 'max' => 255],
        [['config'], 'safe']
    ];
}

现在您可以在您的 View 中设置这样的输入

<?= $form->field($model, 'config[ga_id]', ['labelOptions' => ['label' => 'Google Analytics Tracking ID']])->textInput(['maxlength' => true]) ?>

关于php - Yii2 将表单字段数组保存到单个数据库字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002068/

相关文章:

php - 查找居住在指定距离之间的用户(使用用户的邮政编码)

javascript - 隐藏复选框的标签 - Yii2

php - 在 Yii2 中使用 Gii 从数据库 View 创建 CRUD

php - 将数据插入表 - 主键约束

PHP:mysql_connect() 无法通过命令行运行

java - 在对象数组中找到第一个空槽

java - 搜索字符串数组

javascript - Object.keys在IE11中工作的解决方法是什么?

php - 使用 Yii2 将 Android 表情符号从 Firebase 保存到 MySQL

php - 如何在软删除模型上使用资源 Controller 的 show 方法?