0

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

提交表单 示例错误后我得到的错误

查看页面:

 <?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) );

    }

  }
4

1 回答 1

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 它将再次显示页面并显示错误,因为您已经验证了模型。

还有1件事,我认为这行不通

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

你可能想做

$model->created_time = new \yii\db\Expression('NOW()');
于 2016-05-30T09:42:40.137 回答