0

I want to save Task model, but cannot do it without define date. I have boolean attribute allDay (checkbox in view) and if it set in TRUE date format should be d-m-Y; else 'd-m-Y H:m'. How to define this condition in rules() method?

Next code not work:

public function rules() {
    return [
        [['title', 'user_id'], 'required'],
        [['description'], 'string'],
        [['start', 'end'], 'date', 
            'format' => $this->allDay ? 'php:d-m-Y' : 'php:d-m-Y H:i'],
    ];
}
Oleg Sg
  • 5
  • 4

1 Answers1

0

You can use inline validator for this or set condition in rules. For condition do this:

[['start', 'end'], 'date', 'format' => 'php:d-m-Y', 'when' => function ($model) {
    return $model->allDay;
}],
[['start', 'end'], 'date', 'format' => 'php:d-m-Y H:i', 'when' => function ($model) {
    return !$model->allDay;
}],
Bizley
  • 17,392
  • 5
  • 49
  • 59