0

I am using Yii 1 for my project. I have 5 fields in a form, which must be filled. There's no problem with that - a simple validation rule in model. However, there is one more field, which is not required. But if it is filled, other 5 fields must become not-required. How should I define such validation rules in rules() method in model?

Thank you in advance very much!

Ben
  • 99
  • 2
  • 6

2 Answers2

0

Try playing with scenarios. When you validate your data, check if this field is filled and create new model with specific scenario.

Look here

0

you can create your own custom validation rule so you can skip scenarios, you will need to:

Stating that:

$model->TRIGGERATTR = is the attribute that if informed is going to indicate that the other 5 are required
$model->ATTR1 = one of the five other attributes 
$model->ATTR2 = two of the five other attributes
.
.
. and so on...
  1. Declare your rule inside your model like : array('ATTR1, ATTR2, ATTR3, ATTR4, ATTR5','{NameofRule}Validator'),

  2. Create a custom validation inside your components/validators/general/{NameofRule}Validator

    with the following code

class {NameofRule}Validator extends CValidator { public function validateAttribute($model, $attribute) { if((isset($model->TRIGGERATTR))&&(!is_null($model->TRIGGERATTR)) { if(!isset$model->$attribute||is_null($model->$attribute)) { $this->addError($model, $attribute, 'Is not Informed and it should be'); } } } }

Don´t forget to add your comments and mark as solved ;-)

DiegoCoderPlus
  • 760
  • 6
  • 14