使用Ajax,Yii2 ActiveForm验证唯一字段

时间:2015-12-24 04:30:33

标签: php ajax yii2 yii2-advanced-app

我是Yii的新手,无法弄清楚ajax验证如何与ActiveForm一起使用。 在我的模型中,我有独特的领域:

public function rules()
    {
        return [
             //...
            [['end_date'], 'unique'], //ajax is not working 

            [   'end_date', //ajax is working
                'compare',
                'compareAttribute'=>'start_date',
                'operator'=>'>=',  
                'skipOnEmpty'=>true,
                'message'=>'{attribute} must be greater or equal to "{compareValue}".'
            ],
        ];
    }

比较规则使用ajax验证并且工作正常,但unique不是。我试图在表单上启用ajax验证:

  <?php $form = ActiveForm::begin( ['id' => 'routingForm', 'enableClientValidation' => true, 'enableAjaxValidation' => true]); ?>

但不知道下一步该做什么。

控制器:

public function actionCreate()
{
    $model = new Routing();
    $cities = [];     
    if ($model->load(Yii::$app->request->post()) && $model->save()) {            
        return $this->redirect(['index']);
    } else {
        return $this->renderAjax('create', [
            'model' => $model,
            'cities' => $cities
        ]);
    }
}

我知道我可以在end_date更改事件和表单submit上对控制器进行ajax调用,但不确定如何使所有适当的css显示错误。

2 个答案:

答案 0 :(得分:1)

您需要在控制器中使用Yii::$app->request->isAjax

public function actionCreate()
{
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ActiveForm::validate($model);
      }
   if ($model->load(Yii::$app->request->post()) && $model->save()) {
       return $this->redirect(['index']);
    } else {
        return $this->renderAjax('create', [
          'model' => $model,
          'cities' => $cities
        ]);
}
}

答案 1 :(得分:1)

在控制器中试用此代码......

public function actionCreate()
{
    $model = new Routing();
    $cities = []; 

    if(Yii::$app->request->isAjax){
        $model->load(Yii::$app->request->post());
        return Json::encode(\yii\widgets\ActiveForm::validate($model));
    }

    if ($model->load(Yii::$app->request->post()) && $model->save())  {            
        return $this->redirect(['index']);
   } else {
    return $this->renderAjax('create', [
        'model' => $model,
        'cities' => $cities
    ]);
}
}