Validating a model depending on a check box value

Hi :) ,

I’m using two models in a single form, say ‘company’ and ‘branches’. ‘branches’'s fields are hidden. They are shown only when a checkbox field of ‘company’ is checked. But since both models are in the same form, ajax validation affects them both. I’m searching for a way to validate the second model (ie, ‘branches’) according to the value of the checkbox of ‘company’.

Thank You,

Hi!

I have not tested below code, but I think it should work somehow like this.

You can write your own ajax-validation action in Controller.

In your form:




$form = ActiveForm::begin([

   'id' => 'myFormId',

   // enable ajax validation

   'enableAjaxValidation' => true, 

   // define the action for ajax-validation with "controllername/actionName"

   'validationUrl' => ['myController/ajax-validation'], 

   // clientSide validation can give different result than your custom ajax-validation action 

   // so better disable clientSide OR learn how to modify the clientSide validation like the ajax one.

   'enableClientValidation'=> false, 

]);



Now you can do in your controller for example:

(just example code for understanding)




public function actionAjaxValidation(){

   $request  = Yii::$app->request; 

   $response = Yii::$app->response;


   // populate modelA 

   $modelA = new ModelA; 

   $modelA->load($request->post()); 


   // check if your wanted value is set

   if($modelA->checkBoxField == 1){

      // now populate modelB  

      $modelB = new ModelB; 

      $modelB->load($request->post());

    

      // validate both and return result 

      $response->format = Response::FORMAT_JSON;

      return ArrayHelper::merge(

            ActiveForm::validate($modelA),

            ActiveForm::validate($modelB),

      );

   }

   // since $modelA->checkBoxField has not your required value: 

   // validate and return only $modelA 

   else{ 

      $response->format = Response::FORMAT_JSON;

      return ActiveForm::validate($modelA);

   }

}



Hope this helps.

@ALL - if this is total bullshit, please correct me and show better way. :)

Best Regards

Thank You!!!!

I will try it and update soon… :)

Sorry for the late reply…

It worked for me…

Thanks !!!!