R
R
Roman2015-06-24 16:03:13
Yii
Roman, 2015-06-24 16:03:13

Yii2 how to correctly create complex forms with dependencies and validate them?

We need to create a large form, with steps and with the ability to show and not show certain fields depending on the user's choice. What options are there to achieve this?
And just as interesting is how to validate with dependencies on the yii2 side

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Mironyuk, 2015-06-24
@serieznyi

This is the first solution that came to my mind. Correct me if I'm wrong about anything.
This code has not been tested for functionality, it is only a concept.
Controller

class ControllerForm extends \yii\web\Controller
{
    public function actionCreate()
    {
        $post = Yii::$app->request->post();
        $step = Yii::$app->request->post('step', 'step1');
        $model = ModelForm::model($step);
        $model->attributes = $post;

        if ($model->load($post) && $model->validate()) {
            if ($step === 'stepLast' && $model->save()) {
                return $this->redirect(Url::toRoute(['index']));
            }
        }

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

Model
class ModelForm extends ActiveRecord
{
    public function rules()
    {
        return [
            [['field1', 'field2'], 'required', 'on' => 'step1'],
            [['field3'], 'required', 'on' => 'step2'],
            [['field1', 'field2', 'field3'], 'safe', 'on' => ['step1', 'step2', 'stepLast']]
        ];
    }
}

view
$form = ActiveForm::begin([
    'layout' => 'horizontal',
]);
 echo $form->field($model, 'name', ['options' => ['class' => 'name '.$model->scenario]]);
ActiveForm::end();

css
.name.step1 {
     display: block;
}

.name.step2 {
     display: none;
}

UP1
The Yii2 documentation has information on using multiple models on a form
www.yiiframework.com/doc-2.0/guide-input-multiple-...

M
Maxim Timofeev, 2015-06-24
@webinar

Just like usual. You can also do ajax validation. You can file a separate model for each step and load the steps via ajax. There are many options. Could you describe the problem you see more specifically.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question