Reputation: 185
I'm building a cakephp 3 app (cakephp v3.3.2 that is) and I have a problem getting dates displayed in the chosen locale (de_DE).
The database field in my example is invoice_date
, which is of type DATE (stored in a mysql DB).
I want to use a date picker in the web page ("zebra_datepicker"), so in the view I use a single text entry field for the date instead of the three drop-downs that are displayed by default:
echo $this->Form->input('invoice_date', [ 'type' => 'text' ]);
To get the date displayed in the German format dd.mm.YY
I changed the global locale setting to
ini_set('intl.default_locale', 'de_DE');
in config/bootstrap.php
.
For testing, I created a new record in the database and set the invoice_date to 2016-09-02
(Y-M-D).
If I call the edit
action of my controller now, I get a default value of 02.09.16
in the form, which is correct. But if I submit the form back, the database value of the field is changed into 2002-09-16
!
Do I need some extra code in the controller to change the date format back into its original form? Is this a bug in the localization code of cakephp or did I miss something? Note, that my controller just uses patchEntity
to process the posted data.
I already tried adding date('invoice_date', 'dmy')
in the validationDefault method of the table object, but this didn't change anything:
$validator
->date('invoice_date', 'dmy')
->requirePresence('invoice_date', 'create')
->notEmpty('invoice_date');
Thanks for your help!
Upvotes: 1
Views: 1342
Reputation: 185
I just found the solution to my problem: in bootstrap.php, I had to add:
Type::build('date')->useLocaleParser();
Type::build('datetime')->useLocaleParser();
With that, I can enter dates like 31.12.16
(d.m.y) and the date gets correctly saved in the database. This works with the simple validator:
$validator
->date('invoice_date')
->notEmpty('invoice_date');
To also support dates like 31.12.2016
(d.m.Y), I had to add an extra parameter to the date validator, like this:
$validator
->date('invoice_date', 'dmy')
->notEmpty('invoice_date');
Upvotes: 1