0
votes

I have set up many forms using ActiveForm with Yii2 and it always populate the fields with the correct $_POST data on errors, however I am having problems doing this with forms that are initially filled with data, such as users who want to update existing values - on submit if they get an error the fields always contain the initial value and not the $_POST value.

Here is an example of my form:

$form = ActiveForm::begin();

<?=$form->field($model, 'site_url', ['inputOptions' => ['value' => Yii::$app->params['settings']['site_url']]]); ?>

ActiveForm::end();

I was hoping Yii would automatically override the initial value since it was a POST and use the value of the model $site_url property, but unfortunately this is not the case.

Is there a easy way to handle this? ... a possible way I thought of was to avoid setting the value via the fields and instead set the model property values to the initial values and then Yii should automatically load those values in and on post it will have the $_POST values.

...unless there an easier/better way?

2

2 Answers

0
votes

One option would be checking if it has a loaded value, and if not I would then set the value in params:

$form->field($model, 'site_url', 
    ['inputOptions' => 
      ['value' => (!empty($model->site_url) ? 
        $model->site_url : Yii::$app->params['settings']['site_url']]]);
0
votes

Definite values in controller before you pass model to view... For example

// If you using existing model, in this example update action
public function actionUpdate($id)
{
     $model = $this->findModel($id);
     $model->site_url = 'your value';

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

// If you creating new model and passing values to attributes
public function actionCreate($id)
{
     $model = new Model;
     $model->site_url = 'your value';

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

In this case, when form is submitted you will get values from inputs you have change.