Answer the question
In order to leave comments, you need to log in
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
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]);
}
}
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']]
];
}
}
$form = ActiveForm::begin([
'layout' => 'horizontal',
]);
echo $form->field($model, 'name', ['options' => ['class' => 'name '.$model->scenario]]);
ActiveForm::end();
.name.step1 {
display: block;
}
.name.step2 {
display: none;
}
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 questionAsk a Question
731 491 924 answers to any question