如何在 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/