Search code examples
phpyii2yii2-modelyii2-validation

How to set date format depending on incoming other attribute value in Yii2 model


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

Solution

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