How to validate tabular data in yii?

前端 未结 2 1810
清歌不尽
清歌不尽 2021-01-23 12:07

I have created a form which allows user to save tabular data. I have followed this tutorial . I have managed to add multiple instance for a Model and I am getting the data in th

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 12:30

    There is no inbuilt mechanism in Yii to ajax validation for tabular data. I implemented custom validation using jquery for this purpose. Below is the code that I used to create a custom ajax validation for tabular data.

    Controller: It assigns the value passed to the model attribute and returns any error for the attribute.

    public function actionValidateData($value,$name)
    {
        $model = new BusinessPartner;
        $model->setAttribute($name, $value);
        $model->validate();
        echo CHtml::error($model,$name);
        Yii::app()->end();
    }
    

    Jquery function to make ajax call and show the messages. I have added class 'businessPartner' to all the fields of the model.

    $(document).on('blur','.businessPartner',function(e){
        e.preventDefault();
        var id= $(this).attr('id');
        var name= $(this).attr('rel');
        $.ajax({
            url:"createUrl('user/validatedata'); ?>",
            type: "GET",
            data: 'value='+$.trim($(this).val())+'&name='+ name,
            success :function(data){
                if($.trim(data))
                {   
                    if(!$('#'+id).hasClass('error'))
                    {
                        $('#'+id).addClass('error');
                        $('#'+id).prev().addClass('error');
                        $('#'+id).after(data);
                    }
                }
                else
                {
                    if(!$('#'+id).parent().hasClass('success'))
                    {                       
                        $('#'+id).removeClass('error');
                        $('#'+id).prev().removeClass('error')
                        $('#'+id).next().remove()
                        $('#'+id).parent().addClass('success');
                    }
                }
    
            },
            error:function(){
            },
        });
    });
    

提交回复
热议问题