silintzir
silintzir

Reputation: 792

Initial Values for an array-type attribute in Yii2 Model

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')]]

Upvotes: 0

Views: 1880

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133370

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

Upvotes: 2

Related Questions