yii2验证提交时的表单错误

时间:2016-05-30 07:20:20

标签: yii2 yii2-validation

我的问题:我尝试在某些字段上验证用户输入。我已经在某些领域创建了规则。提交表单时,它会以json格式显示错误消息并停在那里。

提交表单后我得到的错误 sample error

查看页面:

 <?php $form = ActiveForm::begin([
            'id'=>'create_company',
            'method'=>'post',
            //'enableAjaxValidation' => true,
            'enableClientValidation' => true,
        ]); ?>
<?php echo $form->errorSummary(array($model,$memberPlan)); ?>
<h4><?php echo Yii::t('app', 'Personal Information'); ?></h4>
<div class='container-fluid'>

    <div class='col-sm-4'>
        <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
    </div>

型号:

public function rules()
{
    return [
        [['parent_id', 'gender_id', 'marital_status_id', 'id_type', 'company_id', 'department_id', 'designation_id', 'employment_type_id', 'dependent_type_id', 'cost_centre_id', 'location_id', 'waiting_period', 'relation_id', 'state_id', 'region_id', 'bank_id', 'record_status_id', 'hms_uid', 'status_id', 'created_by', 'modified_by'], 'integer'],
        [['name', 'company_id', 'department_id', 'designation_id', 'policy_no', 'plan_name','effective_coverage_date'], 'required'],
        [['dob', 'hired_date', 'confirmation_date', 'first_issue_date', 'effective_coverage_date', 'fullfledge_date', 'reinstatement_date', 'reject_date', 'take_over_date', 'due_date', 'termination_date', 'file_received_date', 'record_status_date', 'created_time', 'modified_time'], 'safe'],
        [['race', 'grade', 'division', 'employee_no', 'termination_reason', 'member_no', 'client_member_id', 'address1', 'address2', 'address3', 'city', 'postcode', 'account_no', 'payee_name', 'policy_no', 'plan_name', 'product_type', 'plan_code', 'decission_flag', 'card_no', 'vip_remark', 'remarks', 'dba_remarks', 'file_name', 'supervisor_code', 'hr_code'], 'string'],
        [['salary'], 'number'],
        [['vip'], 'boolean'],
        [['name'], 'string', 'max' => 120],
        [['nationality', 'coverage'], 'string', 'max' => 2],
        [['id_no', 'alternate_id_no'], 'string', 'max' => 24],
        [['phone', 'mobile', 'fax'], 'string', 'max' => 20],
        [['email', 'alternate_email'], 'string', 'max' => 100],
        ['effective_coverage_date','checkEffectiveCoverageDate', 'on'=>'create'],
        ['first_issue_date','checkFirstIssueDate', 'on'=>'create'],
        ['termination_date','checkTerminationDate', 'on'=>'create'],
        ['email','email'],
        ['termination_date','checkTerminationDate', 'on'=>'update'],

    ];
}
public function checkEffectiveCoverageDate($attribute, $params) {

    if ( !empty($this->effective_coverage_date) AND $this->policy_id != '' ) {

        if (!$this->withinPolicyStartAndEndDate($this->policy_id, $this->effective_coverage_date) ) {
            $this->addError($attribute, 'Effective Coverage Date cannot be before policy start and end date');
        }
    }

}

控制器:

if ( $model->load(Yii::$app->request->post()) && $memberPlan->load(Yii::$app->request->post())) {

  $plan = Plan::find()->where('id = :id',['id'=>$memberPlan->plan_id])->one();
  $policy = Policy::find()->where('id = :id',['id'=>$plan->policy_id])->one();

  $model->plan_name = $plan->name;
  $model->policy_no = $policy->policy_no;
  $model->policy_id = $policy->id;

  $model->created_by = $userid;
  $model->created_time = 'now()';

  $valid = $model->validate();
  $valid = $memberPlan->validate() && $valid;

  if ( $valid ) {

    $transaction = \Yii::$app->db->beginTransaction();
    try {

        $model->setSearchPath($userLogin->getClientCode());

        $model->save();

        $memberPlan->member_id = $model->id;
        $memberPlan->plan_id = $memberPlan->plan_id;
        $memberPlan->start_date = $model->effective_coverage_date;
        $memberPlan->created_by = $userid;
        $memberPlan->created_time = 'now()';

        $memberPlan->save();

        $transaction->commit();
        return $this->redirect(['view', 'id' => $model->id]);

    } catch (Exception $e) {
        $transaction->rollBack();
    }

  } else {

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) &&
    $memberPlan->load(Yii::$app->request->post())) {

      Yii::$app->response->format = 'json';
      return array_merge(ActiveForm::validate($model),ActiveForm::validate($memberPlan) );

    } else {

      Yii::$app->response->format = 'json';
      $error = ActiveForm::validate($model);
      return array_merge($error, ActiveForm::validate($memberPlan) );

    }

  }

1 个答案:

答案 0 :(得分:0)

您的操作顺序是错误的。首先,你不使用ajax验证,所以检查没有意义。

if (Yii::$app->request->isAjax

这永远不会是正确的,因为你不使用ajax。

之后你正在做

  Yii::$app->response->format = 'json';
  $error = ActiveForm::validate($model);
  return array_merge($error, ActiveForm::validate($memberPlan) );

您正在明确地将响应设为ajax并将其发回。它完全按照你告诉它的方式工作。

可能你想删除

} else {
      Yii::$app->response->format = 'json';
      $error = ActiveForm::validate($model);
      return array_merge($error, ActiveForm::validate($memberPlan) );

如果删除此其他内容,则无效模型将传递给视图(假设您在此代码后呈现视图),并且每个字段下都会显示错误。

如果您确实要启用ajax验证,只需将控制器代码更改为:

//check ajax validation first
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && $memberPlan->load(Yii::$app->request->post())) {

          Yii::$app->response->format = 'json';
          return array_merge(ActiveForm::validate($model),ActiveForm::validate($memberPlan) );

        }

//normal check second    
    if ( $model->load(Yii::$app->request->post()) && $memberPlan->load(Yii::$app->request->post())) {

      $plan = Plan::find()->where('id = :id',['id'=>$memberPlan->plan_id])->one();
      $policy = Policy::find()->where('id = :id',['id'=>$plan->policy_id])->one();

      $model->plan_name = $plan->name;
      $model->policy_no = $policy->policy_no;
      $model->policy_id = $policy->id;

      $model->created_by = $userid;
      $model->created_time = 'now()';

      $valid = $model->validate();
      $valid = $memberPlan->validate() && $valid;

      if ( $valid ) {

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $model->setSearchPath($userLogin->getClientCode());

            $model->save();

            $memberPlan->member_id = $model->id;
            $memberPlan->plan_id = $memberPlan->plan_id;
            $memberPlan->start_date = $model->effective_coverage_date;
            $memberPlan->created_by = $userid;
            $memberPlan->created_time = 'now()';

            $memberPlan->save();

            $transaction->commit();
            return $this->redirect(['view', 'id' => $model->id]);

        } catch (Exception $e) {
            $transaction->rollBack();
        }
    }

重点是,如果$ valid = false,它会再次显示页面,但是因为你已经验证了模型,所以会有错误。

还有一件事,我认为这不会起作用

$model->created_time = 'now()';

您可能想要

$model->created_time = new \yii\db\Expression('NOW()');