trntv / yii2-datetime-widget

Yii2 Date/Time Widget
8 stars 14 forks source link

Exception Thrown when KeepInvalid is set a true #18

Open k3bra opened 5 years ago

k3bra commented 5 years ago

When we have KeepInvalid option set as true and we submit a not supported date (ex 2018-10-10 10) we get an Exception thrown.

The problem happens here when call Yii::$app->formatter->asDatetime("2018-10-10 10") to a wrong date

 $this->options['value'] = array_key_exists('value', $this->options)
                ? $this->options['value']
             : Yii::$app->formatter->asDatetime($value, $this->phpDatetimeFormat);
}
k3bra commented 5 years ago

Possible solution is to check if the model has errors and only apply the formatter when it doesn't have errors.

This would work:

     if ($value !== null && trim($value) !== '') {
            if (!array_key_exists('value', $this->options)) {
                if (!$this->model->hasErrors()) {
                    $this->options['value'] = Yii::$app->formatter->asDatetime($value, $this->phpDatetimeFormat);
                }
            }
        }