I am working with a field which is defined as ‘date’ in my model, and want to input/output dates in dd/mm/yyyy format in the user interface, so have set that up as the Formatter dateFormat in my web.php config file. That causes dates to display correctly in grids or detail views if I add a :date suffix to the field name, and the DatePicker widget uses that format by default.
My problem is in a controller action that reads a record, toggles a flag in it (which has nothing to do with the date field), and attempts to do a save, which fails because the date field fails validation. It seems it is stored internally in the sql format yyyy-MM-dd when read in from the database, and that the validation is checking for dd/MM/yyyy format on output.
In this case, I could get around the problem by calling save with the validation parameter set to false, but the problem could occur whenever I want to modify fields other than the date and then save. It doesn’t seem very kosher for ActiveRecord to store the value in the model in a format that it can’t recognize unless I pass it through the DatePicker interface, when it knows the field is of type date.
Is there a standard approach that will take care of all the date fields I will be eventually using, without requiring lots of duplicated work? Define a date validation function that will accept formats in either the format specified in dateFormat, or in yyyy-MM-dd format? (if so, where would the standard place be to put it in the yii2 directory structure) Define different scenarios to control which fields get validated? (seems tedious…) Define an event handler or behavior which converts all yyyy-MM-dd dates to my desired format after reading them in, for all record types? Something else?
It if makes any difference, I am working with a postgresql database. I’m fairly new to Yii, so hope this I am not missing something obvious here.