Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format date fields before save in CakePHP 3?

I used this in AppController:

Time::setToStringFormat('dd/MM/YYYY');

The date field in my form is a input type "text" to allow my user writes something like 31/12/2015.

However when I try to save (MySQL date) I get some errors of Time Class because inside the table the value now is 00-00-0000

Alunos Controller code

Thanks !

like image 509
celsowm Avatar asked Mar 30 '15 00:03

celsowm


2 Answers

My final solution was this on bootstrap:

date_default_timezone_set('America/Sao_Paulo');
setlocale(LC_ALL, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');

Type::build('time')->useImmutable();
Type::build('date')->useImmutable()->useLocaleParser();
Type::build('datetime')->useImmutable()->useLocaleParser();
Type::build('timestamp')->useImmutable();

\Cake\I18n\Time::setToStringFormat('dd/MM/yyyy HH:mm:ss');
\Cake\I18n\Date::setToStringFormat('dd/MM/yyyy');
\Cake\I18n\FrozenTime::setToStringFormat('dd/MM/yyyy HH:mm:ss');
\Cake\I18n\FrozenDate::setToStringFormat('dd/MM/yyyy');

\Cake\I18n\I18n::locale('pt-BR'); //new !

Type::build('decimal')->useLocaleParser();
Type::build('float')->useLocaleParser();
like image 113
celsowm Avatar answered Sep 23 '22 18:09

celsowm


maybe this could help someone.

public function beforeSave($event, $entity, $options) {
    $entity->dateField = date('Y-m-d', strtotime($entity->dateField));
}
like image 30
SNA Avatar answered Sep 22 '22 18:09

SNA