0

New to yii2 so im trying to figure out how to use the required rule but only when a certain field is checked, as the form is has a radio field which allows a new user to create an account as a personal account or as a business account.

I have used use_vat_number as an sample radio button.

public function rules(){
    return [
        ['vat_number', 'required' , 'when' => use_vat_number = 1],//the idea
    ];
}
user759235
  • 2,147
  • 3
  • 39
  • 77

2 Answers2

1

Refer Yii2 when and whenClient property

public function rules() {
   return [
       ['vat_number', 'required', 'when' => function ($model) {
            return $model->use_vat_number == 1;
        }, 'whenClient' => "function (attribute, value) {
               var opValue = $('input:radio[name=\\'Here Radio Button Name\\']:checked').val();
               return opValue==1;
            }",
        ],
   ];
}
vishuB
  • 4,173
  • 5
  • 31
  • 49
0

You should use anonymous function to configure when property:

public function rules(){
    return [
        [
            'vat_number', 'required' , 
            'when' => function ($model) {
                 return $model->use_vat_number == 1;
            },
        ]
    ];
}
rob006
  • 21,383
  • 5
  • 53
  • 74