A trip through the source code, specifically Model::deconstruct()
told me that Cake's native intelligence doesn't run this deep. It expects the full component granularity provided by its own datetime input (i.e. separate datetime components for month, day, year, hour, minute and meridian). I wanted a better user experience, so I wanted to use a date picker that stores the entire date as a single component. To do that I had to get creative.
What I chose to do was to override the Model::deconstruct()
method to break down the date into its components. Here's some code to help visualize the solution I expect to deploy:
#
# In my form (views/events/_form.ctp)
# When rendered, the input names resolve to data[Event][start_time][date],
# data[Event][start_time][hour], data[Event][start_time][minute],
# data[Event][start_time][meridian]
#
<div class="input datetime required">
<?php echo $this->Form->input( 'Event.start_time.date', array( 'type' => 'text', 'label' => 'Start Time', 'div' => false, 'class' => 'date' ) ) ?>
<?php echo $this->Form->input( 'Event.start_time', array( 'type' => 'time', 'label' => false, 'div' => false, 'class' => 'time', 'empty' => true ) ) ?>
</div>
#
# In my model (/models/event.php)
#
function deconstruct( $field, $data ) {
$type = $this->getColumnType( $field );
if( in_array( $type, array( 'datetime', 'timestamp' ) ) ) {
if( isset( $data['date'] ) && !empty( $data['date'] ) ) {
$date = date( 'U', strtotime( $data['date'] ) );
if( $date ) {
$data['month'] = date( 'm', $date );
$data['day'] = date( 'd', $date );
$data['year'] = date( 'Y', $date );
}
}
}
# Now the date is broken down into components that the
# well-vetted parent method expects. Let it do the heavy
# lifting.
return parent::deconstruct( $field, $data );
}
For clarity, I've excluded the javascript code that creates the picker itself. It's a simply jQuery UI behavior applied to the data[Event][start_time][date]
field and isn't germane to the solution. Suffice to say, when the date
textbox receives the focus a very pretty calendar appears.
In my case, I also have several models that have datetime properties so I ended up moving the deconstruct()
override out to a my AppModel
so I can use it throughout. DRY.