Yii check only if there is another field

I have two fields in my form named start date and end date . I want to check end date only if start date present.

In rails we have :if . Do we have something like this in yii ?

+4
source share
4 answers

Define your custom function to test.

define the rule:

 array('end_date','checkEndDate'); 

define custom function:

 public function checkEndDate($attributes,$params) { if($this->start_date){ if(!$this->validate_end_date($this->end_date)) $this->addError('end_date','Error Message'); } } 
+11
source

checking one field based on another can be performed in the model rules method. Here is the rule method.

  ['start_date','required','when'=>function($model) { return $model->end_date != ''; }] 

Hope this helps you.

+2
source

For laziness, add a conditional check to the beforeValidate model beforeValidate :

 if($this->start_date){ if(!$this->validate_end_date($this->end_date)) $this->addError('end_date','Error Message'); } 
+1
source

You can use the validate() method to verify attributes separately , so you can check start_date first and skip checking if there are errors with it, for example:

 <?php // ... code ... // in your controller actionCreate for the particular model // ... other code ... if(isset($_POST['SomeModel'])){ $model->attributes=$_POST['SomeModel']; if ($model->validate(array('start_date'))){ // alright no errors with start_date, so continue validating others, and saving record if ($model->validate(array('end_date'))){ // assuming you have only two fields in the form, // if not obviously you need to validate all the other fields, // so just pass rest of the attribute list to validate() instead of only end_date if($model->save(false)) // as validation is already done, no need to validate again while saving $this->redirect(array('view','id'=>$model->id)); } } } // ... rest of code ... // incase you didn't know error information is stored in the model instance when we call validate, so when you render, the error info will be passed to the view 

Alternatively, you can also use the skipOnError attribute of the skipOnError class :

 // in your model rules, mark every validator rule that includes end_date as skipOnError, // so that if there is any error with start_date, validation for end_date will be skipped public function rules(){ return array( array('start_date, end_date', 'required', 'skipOnError'=>true), array('start_date, end_date', 'date', 'skipOnError'=>true), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, start_date, end_date', 'safe', 'on'=>'search'), ); } 

Hope this helps.
Disclaimer: I'm not sure about the skipOnError solution, it may be affected by the order of validators, you can check it (I have not tested it yet) and find out if it works. Of course, an individual verification solution will work any day.

0
source

Source: https://habr.com/ru/post/1399520/


All Articles