0

If an attribute in a Model holds array data, say Dates, that are populated in a form with multiple rows for this attribute, how may I assign initial values to the array elements so that they display initially in the form when it appears.

In my example, my array-type attribute holds dates and I want each new date row in the form to have different values when the form loads.

<?= $form->field($model, 'datesToPay[]') ?>

I tried to use the DefaultValueValidator filter of Yii2 to assign initial value to the datesToPay array elements but it does not show the value when the form loads.

['datesToPay', 'each', 'rule' => ['default', 'value' => date('Y-m-d')]]

1 Answer 1

2

You can do in the controllerAction before render

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

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

        $model->datesToPay[0] = 'YourValue';

        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. This seems to work the setup I described in the question. My problem comes when I try to use a date picker on the field. I'm using Kartik date picker widget, so obviously the hidden value is set correctly according to your suggested solution but the date picker field (the display value) does not show it and I can't find a way to override the value.
I suggest you of post a new specific question about your datePicker problem .. witn the code for the datePicker too.

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.