【问题标题】:Validate unique field using Ajax, Yii2 ActiveForm使用 Ajax、Yii2 ActiveForm 验证唯一字段
【发布时间】:2015-12-24 04:30:33
【问题描述】:

我是 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 显示错误。

【问题讨论】:

  • 请显示您的控制器代码...
  • 只需阅读官方文档,它已涵盖here

标签: php ajax yii2 yii2-advanced-app


【解决方案1】:

您需要在控制器中使用Yii::$app-&gt;request-&gt;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
        ]);
}
}

【讨论】:

    【解决方案2】:

    在您的控制器中尝试此代码...

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

    【讨论】:

    • 您不应使用Json::encode ,要么即时更改响应格式,要么使用ContentNegotiator
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多