I've searched around here for some time today, but I'm unable to understand why my validators aren't working in my model.
I have a Module with a model "Page" in my code below.
I have 2 attributes that I need to use to validate the model. They are hero_link and hero_linked. If hero_linked is true, I want to require hero_link.
In the guide here, they explain the proper syntax for this kind of validator
I have used this syntax in my model, but it doesn't validate as I'd expect. I've added the whenClient property as well, so I can use client side validation here.
my relevant code is below:
// Page model
namespace common\modules\page\models;
use Yii;
class Page extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['hero_linked',], 'boolean'],
[['hero_linked',], 'required'],
[['hero_link',], 'string', 'max' => 255],
[
'hero_link',
'required',
'when' => function($model) {
return $model->hero_linked == true;
},
'whenClient' => "function (attribute, value) {
return $('#page-hero_linked').val() == '1';
}",
],
];
}
}
// _form view
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'hero_linked')->checkbox() ?>
<?= $form->field($model, 'hero_link')->textInput(['maxlength' => 255]) ?>
<?php ActiveForm::end(); ?>
The required validator is correctly applied, but it seems to be ignoring the when property, and requiring even though my checkbox is unchecked. Is my syntax incorrect, or am I missing a requirement? Any help is appreciated, Thanks in advance!