3
votes

I have this:

<?php echo $this->Form->input('Schedule.0.end_date', array(
    'minYear' => date('Y'),
    'maxYear' => date('Y')+5
)); ?>

I would like to set the default date to something other than today. Is this possible with CakePHP's form helper?

I found a post that showed how do to it with TIME - but trying something similar by setting "day", "month", "year" does nothing.

4

4 Answers

13
votes

You can achieve that using the selected parameter of $this->Form->input();. Try like this:

<?php
echo $this->Form->input('datetime', array(
  'label' => 'Date 1',
  'selected' => array(
    'day' => '',
    'month' => '',
    'year' => '',
    'hour' => '',
    'minute' => '',
    'second' => ''
    )
  ));
/* What's interesting... this will work aswell: */
echo $this->Form->input('datetime', array(
  'label' => 'Date 2',
  'selected' => '0000-00-00 00:00:00'
  ));
?>
5
votes

Just an update for Cake 3.* users: now in order to precompile the datetime fields is necessary to use the 'default' keyword:

echo $this->Form->input('datetime', array(
  'label' => 'Date 2',
  'default' => '2015-09-10 06:40:00'
));
0
votes

The problem with using the 'selected' option in the form helper, is if you submit the form, then the submitted value will be overwritten by the selected value, so if the page reloads because of an error or something, then the user loses what was original submitted.

I prefer to set the default value in the controller if it hasn't already been set, otherwise it will be populated by the last submission.

In Controller:

if (!isset($this->request->data['start_date']))
        $this->request->data['start_date'] = date('Y-m-d', strtotime('-1 month'));

This way the first time the user loads the form, they are presented with a desirable default value, but if they submit the form once and are brought back to it, their selected value is selected still.

0
votes

With CakePHP 2.x,

echo $this->Form->input('end', array(
     'selected' => array(
         'day' => date('d'), 
         'month' => date('m'), 
         'year' => date('Y'), 
         'hour' => date('h'), 
         'min' => date('i'), 
         'meridian' => date('a')
)));

if you want to show month number in English words:

$month = DateTime::createFromFormat('!m', date('m'));
$month->format('F');

echo $this->Form->input('end', array(
     'selected' => array(
         'day' => date('d'), 
         'month' => $month->format('F'), 
         'year' => date('Y'), 
         'hour' => date('h'), 
         'min' => date('i'), 
         'meridian' => date('a')
)));