YII2 : Add Dynamic form fields and their validations

故事扮演 提交于 2019-11-29 06:18:53

Its been a month so guessing this has been solved but for reference for others like me looking for the same and to save having to step thru the framework to find the answer perhaps try something like:

...
use yii\helpers\Json;
...

<?php foreach ($form->attributes as $attribute) {
    $attribute = Json::htmlEncode($attribute);
    $this->registerJs("jQuery('form').yiiActiveForm('add', $attribute);");
} ?>

<?php Pjax::end(); ?>
...

Tested with regards to clientValidation and not with above question so have hacked my solution to hopefully answer above question.

Simple

You should try this

<?php
    $this->registerJs('



            jQuery("#w0").yiiActiveForm("add",{
                "id": "customer-name",
                "name": "name",
                "container": ".field-customer-name",
                "input": "#customer-name",
                "error": ".help-block.help-block-error",
                "validate": function(attribute, value, messages, deferred, $form) {

                    yii.validation.required(value, messages, {
                        "message": "Name be blank bug."
                    });

                    yii.validation.string(value, messages, {
                        "message": "Name must be a string.",
                        "max": 255,
                        "tooLong": "Name should contain at most 255 characters.",
                        "skipOnEmpty": 1
                    });
                }
        });


    ');
 ?>

Changes

  • w0 into your form ID

  • "id": "customer-name" into your input field ID

  • "container": ".field-customer-name" into input field div container class

That didn't quite work for me I had to add these addrow and deleterow functions for my js. I ajax off to get a new row each time then inject it into the DOM after the last row.

// Add the validation for said elements (without this val.validate but I had a validate not an expression error) data is a json object of the db model coming from my ajax controller action.

$.each(data.attributes, function(key, val) {                
val = $.parseJSON(val);         
// The validate method is kept in expression so turn it back into a closure. 
val.validate = eval("var f = function(){ return "+val.validate.expression+";}; f() ;") ;
$('#dal-add-form').yiiActiveForm('add', val);
});

Then to remove the validation:

$.each($(this).parents('.dal-row').find('input, textarea, select'), function() {            
$('#form').yiiActiveForm('remove', $(this).attr('id'));
});     
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!