Yii2: compare start and end time of input in table / array

Is it possible to compare the start and end time in my lower form by checking yii2 client / ajax.

enter image description here

My view file code is:

<?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,
       ]);
   }
}
+4
source share
1 answer

You can define a rule to compare two dates.
First you need to convert them to an integer in order to be able to use the integrated validator. The best way to do this is to specify a date for the unix timestamp before validation and in the format you need after validation.
Add them to 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 a new rule inside your method rules

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; }'],
];

ajax. , js, whenClient .

+1

Source: https://habr.com/ru/post/1622883/


All Articles