0

私は2つのモデル、すなわちaclとuserを持っています。それぞれに独自の検証ルールのセットがあります。ただし、1つのフォーム内のすべての入力フィールドを使用します。

UserControllerには、createActionメソッド内に2つの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
            ));
    }

AjaxValidation

 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();
            }
    }

検証しているフォームは1つだけで、誰でも提案できます

4

1 に答える 1

1

CActiveFormvalidate() ドキュメントから、モデルの配列を渡すことができます。1つの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 に答える