Yii ClientSide Validation on Render Partial not Working

前端 未结 3 1124
借酒劲吻你
借酒劲吻你 2021-02-10 07:22

I have a Yii form which calls a render partial from another model (team has_many team_members). I want to call via ajax a partial view to add members in team/_form. All works (c

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-10 07:35

    The actual problem is that the ActiveForm saves its attributes to be validated in the "settings" data attribute. I see you are already using indexes so what you need to add the new elements to this settings object in order for the validation to work. After the ajax response this is what must be done:

    //Get the settings object from the form
    var settings = $("#form").data('settings');
    //Get all the newly inserted elements via jquery
    $("[name^='YourModel']", data).each(function(k, v) {
        //base attribute skeleton
        var base = {
            model : 'YourModel',
            enableAjaxValidation : true,
            errorCssClass : 'error',
            status : 1,
            hideErrorMessage : false,
        };
    
        var newRow = $.extend({
            id : $(v).attr('id'),
            inputID : $(v).attr('id'),
            errorID : $(v).attr('id') + '_em_',
            name : $(v).attr('name'),
         }, base);
         //push it to the settings.attribute object
         settings.attributes.push(newRow);
     });
     //update the form
     $("#form").data('settings', settings);
    

    ```

    This way the ActiveForm will be aware of the new fields and will validate them.

提交回复
热议问题