用于惟一验证器的Ajax消息


Ajax message for yii unique validator

我试图验证表单对模型在Yii保持ajax验证。我想保持一个字段唯一在我的数据库。我面临的问题是ajax消息没有显示唯一的验证器,但对于所有其他规则,它工作得很好。

请告诉我哪里错了。相关规范如下

<<p> 模型规则/strong>
  public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
       -----------
        ------------
        array('user_code', 'length', 'max'=>20),
        array('user_code','unique','message'=>'This  code already exists. Please try different code', 'className' => 'User',
    'attributeName' => 'user_code',),
    );
}

<?php $form=$this->beginWidget('CActiveForm', array(
                    'id'=>'frm-useraccount',
                    'enableAjaxValidation'=>true,
                    'enableClientValidation'=>true,
                    'action'=>Yii::app()->createUrl('dashboard/index').'#user',
                    'clientOptions'=>array(
                            'validateOnSubmit'=>true,
                    ),
                ));
                ?>
控制器

$objMdl                   = new User;
      $isUserSetUpFormSubmitted     = (isset($postedData['User']))?true:false;
      // handle form submit
      if($isUserSetUpFormSubmitted)
      {
         //validate the model 
          $isMdlValidated = $objMdl->validate($postedData['user_code']);
          if($isMdlValidated)
          {
            //handle insert
          }
          else
         {
            //display model errors
          }
      }

要显示特定字段的错误,您需要在表单中显示错误摘要或错误字段。

错误总结
<?php echo $form->errorSummary($model); ?>

错误字段

<?php echo $form->error($model,'user_code'); ?>

除此之外,您还需要设置控制器以返回ajax验证结果

/**
 * Provides output to controller action request "/dashboard/index"
 */
public function actionIndex() {
    // Prepare login form
    $model = new User('update');
    // Perform AJAX validation if required
    $this->performAjaxValidation($model, 'frm-useraccount');
    // Perform basic validation
    if ($model->attributes = $req->getPost('User')) {
        if ($model->validate()) {
            // Save in DB
            $model->save(false);
            // Show confirmation for user
            Yii::app()->user->setFlash(
                'success',
                Yii::t(
                    'site',
                    'Save successfull.'
                )
            );
            // Refresh
            $this->refresh();
        }
        else {
            Yii::app()->user->setFlash(
                'error',
                CHtml::errorSummary($model)
            );
        }
    }
}
/**
 * Creates data validation output for ajax requests with data from given form ID
 */
protected function performAjaxValidation($model, $formId) {
    /**
     * @var $app CWebApplication
     * @var $req CHttpRequest
     */
    $app = Yii::app();
    $req = $app->getRequest();
    if ($req->getIsAjaxRequest() && $req->getPost('ajax') === $formId) {
        echo CActiveForm::validate($model);
        $app->end();
    }
}

除了你的模型和规则之外,这应该足够显示你需要的错误。

他说的话^^^。除了迪尔所说的,你创建了一个新对象,却没有给它赋任何值。$objMdl->validate($postedData['user_code']);表示验证模型objMdl的属性$postedData['user_code']。这并不意味着验证属性user_code,但无论你插入$postedData['user_code']随机的东西。