2

This has been bugging me for a while now. I would like to use a Javascript datetimepicker, instead of the default set of select boxes that the CakePHP Formhelper generates. The easy solution would seem to be:

echo $this->Form->input('start_time', ['type' => 'text', 'class'=>'datetime']);

But this introduces some other problems as Cake will then convert the values into the locale format. I would also prefer a solution that worked from a general perspective, so I looked into changing the template for the datetime input:

//AppView.php
class AppView extends View
{
public function initialize()
{
    $this->Form->templates(['dateWidget' => '<input type="text" class="datetime" name="{{name}}"{{attrs}}/>']); 
}

}

This, however is as close as I've gotten. What happens is that the Formhelper outputs a nice text input, with an empty name attribute, which defeats the purpose.

I assume this is because the datetimeinput is basically wired to output the select fields, and is thus confused by my approach here.

But what would be the right way to do it?

  • What's the problem with the localized format? Usually that's what you want to show your users instead of this generic `YYYY-MM-DD` SQL format. What you show here is what I alwas do, use `text`, then just configure the JS picker to use the same localized format, and voilà. – ndm Jun 24 '16 at 17:54
  • I think you are right. Would have been nice to be able to do a more streamlined version, but what you say could work. Can the localized format be customized to a pattern somewhere? – Jonas Kvist Jensen Jun 27 '16 at 07:21
  • Actually I still can't make this happen. The input will not validate when using a text input, as Cake uses a time object that seems incompatible with the straight text. – Jonas Kvist Jensen Jun 27 '16 at 08:18
  • If you validate using the internal date validation, then you need to make sure that it uses the same pattern as your input. **http://stackoverflow.com/questions/35676227/cakephp-3-2-change-default-date-format/35677192#35677192** | **http://stackoverflow.com/questions/34896273/cakephp-3-parse-date-with-localstringformat-to-correct-sql-format-and-correct/34896974#34896974** – ndm Jun 27 '16 at 12:29
  • @JonasKvistJensen did you figure it out? I am also using a datetimepicker https://github.com/xdan/datetimepicker and receiving the date through an input/text – Isengo Oct 03 '16 at 18:28

1 Answers1

1

I have temporarily solved this problem by this line:

echo $this->Form->input('date', ['class' => 'datepicker-input', 'type' => 'text', 'format' => 'Y-m-d', 'default' => date('Y-m-d'), 'value' => !empty($item->date) ? $item->date->format('Y-m-d') : date('Y-m-d')]);

This will display a text field, add my datepicker-input class to the field. Show default date value in y-m-d format so that date picker can instantly read the current date.

This way it also save this data in database without any further issue.

rayhan
  • 636
  • 3
  • 9
  • 26