1

I'm trying to use 'type'=> 'datetime-local' in my form to create the date time picker. In the view everything works fine but cakephp can't handle the format of the result. I've tried to cast it to a Cake\I18n\Time but it ignores the set time and is using the current time.

Did anyone use the html5 date time picker in cakephp? Is there any intention to make it the default picker in cake?

The cakephp default picking option with a lot of select boxes is not really handy.

virido
  • 41
  • 1
  • 2

1 Answers1

0

CakePHP doesn't support the format used by the HTML5 datetime-local input (YYYY-MM-DDTHH:MM) out of the box (yet).

You can solve this by for example using a custom/extended database type that adds a proper format to the existing default formats (this will affect all datetime fields/columns), like:

// in src/Database/Type/DateTimeType.php

namespace App\Database\Type;

class DateTimeType extends \Cake\Database\Type\DateTimeType
{
    public function __construct($name = null)
    {
        $this->_format[] = 'Y-m-d\TH:i'; // date() compatible format

        parent::__construct($name);
    }
}
// in config/boostrap.php before `Type::build('datetime')` is invoked

Type::map('datetime', \App\Database\Type\DateTimeType::class);

by parsing the input manually before marshalling:

// in a table class, a behavior, or a listener for the Model.beforeMarshal event

public function beforeMarshal(\Cake\Event\Event $event, \ArrayObject $data, \ArrayObject $options)
{
    if (isset($data['fieldName']) &&
        is_string($data['fieldName'])
    ) {
        $data['fieldName'] = \Cake\I18n\Time::parseDateTime(
            $data['fieldName'],
            "yyyy-MM-dd'T'HH:mm" // ICU compatible format
        );
    }
}

or by enabling localized parsing, and supplying a matching format (this will restrict all datetime fields/columns to this one format):

// in config/bootstrap.php

Type::build('datetime')
    ->useImmutable()
    ->useLocaleParser()
    ->setLocaleFormat("yyyy-MM-dd'T'HH:mm"); // ICU compatible format

See also

ndm
  • 59,784
  • 9
  • 71
  • 110