0

我有两个模型,即 acl 和 user。每个都有自己的一组验证规则。但是,我在一个表单中使用所有输入字段。

在 UserController 中,我在 createAction 方法中有两个 ajax 验证方法

这看起来像这样

 public function actionCreate()
    {
            $model=new user;
            $acl = new acl;


            // Uncomment the following line if AJAX validation is needed

                    $this->performAjaxValidation1($acl);

                    $this->performAjaxValidation($model);



            //$this->performAjaxValidation1($acl);

            //$valid=$model->validate();
            //$valid=$acl->validate() && $valid;



            if(isset($_POST['user'], $_POST['acl']))
            {
                    $model->attributes=$_POST['user'];
                    $acl->attributes=$_POST['acl'];
                    if($model->save() && $acl->save())
                            $this->redirect(array('view','id'=>$model->id));
            }

            $this->render('create',array(
                    'model'=>$model,
                    'acl'=>$acl
            ));
    }

Ajax验证

 protected function performAjaxValidation($model)
    {
            if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
            {
                    echo CActiveForm::validate($model);
                    Yii::app()->end();
            }
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation1($acl)
    {
            if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
            {
                    echo CActiveForm::validate($acl);
                    Yii::app()->end();
            }
    }

只有一种形式可以验证任何人都可以建议

4

1 回答 1

1

CActiveFormvalidate() 文档中,您可以传递模型数组。您只需要声明一个 ajax 验证函数。下面是修改后的代码

控制器动作

 public function actionCreate()
    {
            $model=new user;
            $acl = new acl;


            // Uncomment the following line if AJAX validation is needed

             $this->performAjaxValidation(array($acl,$model));//pass the models as array







            if(isset($_POST['user'], $_POST['acl']))
            {
                    $model->attributes=$_POST['user'];
                    $acl->attributes=$_POST['acl'];
                    if($model->save() && $acl->save())
                            $this->redirect(array('view','id'=>$model->id));
            }

            $this->render('create',array(
                    'model'=>$model,
                    'acl'=>$acl
            ));
    }

Ajax 验证功能

protected function performAjaxValidation($model)
    {
            if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
            {
                    echo CActiveForm::validate($model);
                    Yii::app()->end();
            }
    }
于 2012-08-20T13:40:11.610 回答