如何在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>
Run Code Online (Sandbox Code Playgroud)
当前控制器(我需要知道如何循环数组并保存以及保存表单中的其他常规字段):
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,
]);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我根本不需要对控制器进行任何更改.
您可以在db记录中创建一个字段,例如'config_json`,然后在模型中使用getter和setter定义一个虚拟属性.
public function getConfig()
{
return json_decode($this->config_json);
}
public function setConfig($value)
{
$this->config_json = json_encode($value);
}
Run Code Online (Sandbox Code Playgroud)
还要将您的虚拟财产设置为规则中的安全,以便Massive Assignment正常工作.
public function rules()
{
return [
[['company_id', 'created_at', 'updated_at'], 'integer'],
[['class'], 'required'],
[['config_json'], 'string'],
[['class'], 'string', 'max' => 255],
[['config'], 'safe']
];
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以在视图中设置这样的输入
<?= $form->field($model, 'config[ga_id]', ['labelOptions' => ['label' => 'Google Analytics Tracking ID']])->textInput(['maxlength' => true]) ?>
Run Code Online (Sandbox Code Playgroud)