7

How can I save an array of fields in Yii2 the current/default setup only works for field which aren't array.

Below are the form fields I need to save into the single field:

<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>

Current Controller (I need to know how I can loop through array and save as well as saving other normal fields in my form):

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,
        ]);
    }
}

5 Answers 5

8

In my case I didn't need to make any changes to the controller at all.

You can just make a field in your db record, something like 'config_json` and then define a virtual property with getter and setter in your model.

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

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

Also set your virtual property to be safe in the rules so Massive Assignment works.

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

Now you can set inputs like this in your view

<?= $form->field($model, 'config[ga_id]', ['labelOptions' => ['label' => 'Google Analytics Tracking ID']])->textInput(['maxlength' => true]) ?>
Sign up to request clarification or add additional context in comments.

Comments

2

you can use loadMultiple(), look at this

this is about tabular/multiple input.

Otherwise load the modal you need using load($_POST[your_form_name].

Comments

1

models

public function getNetworkTypeArray()
{
    return explode(',', $this->network_type);
}

public function setNetworkTypeArray(array $value)
{
    $this->network_type = implode(',', $value);
}

controller

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    if ($model->load(Yii::$app->request->post())) {
        $model->setNetworkTypeArray($model->network_type);
        if ($model->save()) {
            return $this->redirect(['index']);
        }
    }

    $model->network_type = $model->getNetworkTypeArray();
    return $this->render('update', [
        'model' => $model,
    ]);
}

Comments

0
$form->field($form, 'email[]')->textInput(['id' => 'email-0']);

will render:

<input type="text" name="Form[email][]" id="email-0">

Please note double square brackets in ($form, 'email[]'). ID attribute must be set explicitly unique, otherwise duplicate IDs will render, which does not conform with W3C/javascript standards.

Comments

0

instead saving in array you can save in string, to that use tne variables as normal in the view, ex: fieldofarray instead fieldofarray[],

and in the controller use the implode function, ex:

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

        if ($model->load(Yii::$app->request->post())) {
          $model->fieldofarray = implode (",",$model->fieldofarray);
          $model->save();

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.