Multi Page Form With Validation

Hi i am having issues trying to create a multipage form. I have read lots of info on this especially this

yii-multi-page-form-wizard-best-practice on stackoverflow

But I am having issues with validation. When trying to move from step one of the form, validation fails because its trying to validate fields that are not in that step.

I then removed validation from each step and instead validated on save. But after doing this i notices none of the data was being stored. So when the validation fails and goes back to the first page the form is empty.

Could anyone see what i am doing wrong?

My controller code is below:





public function actionCreate()

	{

		$model=new Accounts;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['accountsStep2']))

		{

			$this->setPageState('step1',$_POST['Accounts']);

			$model=new Accounts('step1');

			$model->attributes = $_POST['Accounts'];

	

				$this->render('create',array(

					'model'=>$model,

					'formLevel' => '2',

				));


		}

		elseif(isset($_POST['AccountsFinish']))

		{

			$model->attributes=$_POST['Accounts'];

			if($model->save()) {

				$this->redirect(array('view','id'=>$model->accountID));

			} else {

				$this->render('create',array(

				'model'=>$model,

				'formLevel' => '1',

			));	

			}

			

		} else {


			$this->render('create',array(

				'model'=>$model,

				'formLevel' => '1',

			));

		}

	}




All Sorted, Seems i wasnt doing setting the second form to be stateful!

My only other issue is how do i part validate the form. So i can validate fields as we go along.

I think you can achieve your goal with scenarios.

Define validation rules for each step (=>scenario) and use them to validate each step.

I’m building a multi-step registration form. I have scenarios for each step (step1,step2,etc).

In the controller, I check if the model has any errors, always validating using the previous step:




if($_GET['step'])>1) {

   $step-= 1;

} else {

   $step= 1;

}




if ( $_POST ) {

   $userFormModel = new UserForm('step'.$step);

   $userFormModel->attributes = $POST;

   

   if ( $userFormModel->validate() {

       $step = $_GET['step'];

   } else {

       $errors = $userFormModel->getErrors();

   }


}


$this->render( 'step'.$step,

               array('errors',$errors)

);




This is what I came with, from my head right now. Not tested. But I think you got the idea. You’ll be always checking the previous step when calling the controller.

perfect just what i am looking for cheers!

No problem. Did you understand all the logic? I know it is a bit tricky, but a little more flexible than using a lot of information.

I found this Multi-step registration form