I have form fields generated by Yii2 using echo $form->field. When I select 'Pay Now' and submit, the validation should NOT validate the payment person's last name. However, when I select 'Pay Later' and submit, it must validate it as required.
Regardless of what I select, it always treats the field as required. What am I doing wrong?
Select Option:
<select id="singleregisterform-paymentoptionid" name="SingleRegisterForm[paymentOptionId]">
<option value="1">Pay Now</option>
<option value="2">Pay Later</option>
</select>
Text Field:
<input type="text" id="singleregisterform-paymentpersonlastname"
name="SingleRegisterForm[paymentPersonLastname]"
maxlength="40" placeholder="Enter last name">
Yii2 Model Rules:
['paymentOptionId', 'required'],
['paymentPersonTitleId', 'required'],
['paymentPersonLastname', 'string', 'min' => 2, 'max' => 45],
['paymentPersonLastname', 'required', 'when' => function ($model) {
return $model->paymentOptionId == 2;
}, 'whenClient' => "function (attribute, value) {
return $('#paymentOptionId').val() == 2;
}"],
You need to add a ‘whenClient’ rule
https://www.yiiframework.com/doc/guide/2.0/en/input-validation#conditional-validation