Yii2 custom validator not working as guide suggests

只愿长相守 提交于 2019-12-06 02:12:45

I guess this is what you want. First use the property "checked" in the whenClient of the input field to get if the checkbox is checked or not.

The hidden field of the checkbox is not an issue.

The whenClient in hero_linked (checkbox) is used to validate the hero_link (textinput) field on change of the checkbox. So you instantly see if the hero_link (textinput) is required or not.

You don't need any additional js code in your form if you use this rules.

But as you might also see that due to the complete name "page-something" this is really fixed to only the "page" model and i guess also depending on the form name. So you should use some other fixed "id's" for both fields in the form.php so this also would also work if you extend your page model to another class.

[
    'hero_linked', 'required',
    'whenClient' => "function (attribute, value) {
        $('form').yiiActiveForm('validateAttribute', 'page-hero_link');
        return true;
    }",
],
[['hero_link',], 'string', 'max' => 255],
[
    'hero_link', 'required', 'when' => function ($model) {
        return $model->hero_linked == true;
    },
    'whenClient' => "function (attribute, value) {
        return $('#page-hero_linked').prop('checked');
    }",
],

I found out how to make this work. If you use a checkbox, you cannot use only server or client side validation. I had to use both when and whenClient. I had to register a script in my view so the checked attribute would update on the checkbox.

$('label > #page-hero_linked').click(function(event) {
    var checked = $(this).attr('checked');
    if (checked) {
        $(this).removeAttr('checked');
    }else{
        $(this).attr('checked', '');
    };
});

and below is my validation rule.

[['hero_link'],
'required',
'when' => function($model) {
    return $model->hero_linked == true;
},
'whenClient' => "function (attribute, value) {
    return $('#page-hero_linked').attr('checked');
}",],

All in all, pretty simple code to make it work, but not obvious to me that this much is required from the docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!