0

My Problem : I'm trying to validate user input using on certain fields. I have created rules on certain fields. When submit the form, it display the error message in json format and stop there.

Error that i got after submit the form sample error

View page :

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

Model :

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

}

Controller :

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

    }

  }
kasmawati
  • 51
  • 2
  • 9
  • "*.. it display the error message in json format and stop there.*" So, What You Actually Want? You Didn't Described In Question What You Are Looking For.? – Nana Partykar May 30 '16 at 09:28

1 Answers1

0

The order of the operations you have is wrong. First of all you do not use ajax validation, so there is no point in your check.

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

This will never be right because you do not use ajax.

Afterwards you are doing

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

You are explicitly making the response ajax and sending it back. It works exactly how you told it to.

Probably you want to remove

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

If you remove this else the invalid models will be passed to the view (assuming you are rendering a view after this code) and errors will show up under each field.

If you do want to enable ajax validation, you can just change the controller code to:

//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();
        }
    }

The point is that if $valid = false it will show the page again with errors on it because you already validated the models.

1 more thing, I do not think this will work

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

You probably want to do

$model->created_time = new \yii\db\Expression('NOW()');
Mihai P.
  • 9,307
  • 3
  • 38
  • 49
  • It's working now. I have another problem, I want ['termination_date','checkTerminationDate', 'on'=>'update'] rule to be validate on update action. I have added $model->scenario = "update" on action controller, but when updating the form it did not validate the termination_date field – kasmawati May 31 '16 at 02:49
  • accept the answer and ask another question where you put in the code. In this question you did not put the code for that function so there is no way to check your code. – Mihai P. Jun 02 '16 at 09:24