PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 23, 2022

[FIXED] Use localized date format with date picker in cakephp 3

 January 23, 2022     cakephp, cakephp-3.0, date, datepicker, locale     No comments   

Issue

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!


Solution

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');


Answered By - Wile E. Genius
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing