4

Is it possible to compare start and end time in my below form in yii2 client/ajax validation.

enter image description here

My view file code like this:

<?php foreach ($model->weekDaysList as $index => $value) : ?>
    <div class="row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm-2">
            <?= $form->field($model, "[$index]td_day")->checkbox(['label' => $value]) ?>
        </div>
        <div class="col-sm-3">
            <?= $form->field($model, "[$index]td_from") ?>
        </div>
        <div class="col-sm-3">
            <?= $form->field($model, "[$index]td_to") ?>
        </div>
    </div>
<?php endforeach; ?>

controller code:

public function actionSchedule()
{
   $model = new TimetableDetails();
   $model->scenario = 'MultiSchedule';
   $model->attributes = Yii::$app->request->get('sd');

   if ($model->load(Yii::$app->request->post())) {
       if (Yii::$app->request->isAjax) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\widgets\ActiveForm::validate($model);
       }
   }    

   if (Yii::$app->request->isAjax) {
       return $this->renderAjax('schedule', [
             'model' => $model,
       ]);
   } else {
       return $this->render('schedule', [
             'model' => $model,
       ]);
   }
}
Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
Hiren Bhut
  • 948
  • 1
  • 11
  • 17

1 Answers1

1

You can define a rule for comparing two dates.
First you need to convert them to integer in order to be able to use integrated validator. The best way to do it to cast date to unix timestamp before validation and to the format you need after validation.
Add these in your model:

public function beforeValidate() {
    $this->td_to = strtotime($this->td_to);
    $this->td_from = strtotime($this->td_from);
    return parent::beforeValidate();
}

public function afterValidate() {
    $this->td_to = date(FORMAT, $this->td_to);
    $this->td_from = date(FORMAT, $this->td_from);
}

Add new rule inside your rules method

return [
    // rules
    ['td_to', 'compare', 'operator' => '<', 'type' => 'number', 'compareAttribute' => 'td_from', 'whenClient' => 'js:function () { /* validate values with jQuery or js here and if valid return true */ return true; }'],
];

This would work on ajax validation. In order to make client validation you need to add js function which validates the values and assign it to whenClient key of the rule.

iamawebgeek
  • 2,192
  • 1
  • 12
  • 30
  • Your code is not working. I getting null value in `beforeValidate()` function of `td_to` and `td_from` please check. – Hiren Bhut Jan 05 '16 at 11:22