Tuesday, March 12, 2013

FormHelper cannot set default meridian when using minute interval and default minute value

In my application, the following is expected to output the hour, minute, and meridian <select>s for a 12-hour time with 4:30pm selected by default:

<?php
    echo $this->Form->input('time_example', array(
        'interval' => 5,
        'timeFormat' => '12',
        'type' => 'time',
        'selected' => array(
            'hour' => '4',
            'min' => '30',
            'meridian' => 'pm'
        )
    ));
?>


But the default selected time is actually displayed as 4:30am.

After some fiddling, I found that it will correctly default to 4:30pm if interval is removed from the options, and it will correctly default to 4:00pm if min is removed from the options.

I dug into FormHelper.php and found this, starting at line 2246 (in CakePHP version 2.2.3):

if (!empty($interval) && $interval > 1 && !empty($min)) {
    $current = new DateTime();
    if ($year !== null) {
        $current->setDate($year, $month, $day);
    }
    if ($hour !== null) {
        $current->setTime($hour, $min);
    }
    $change = (round($min * (1 / $interval)) * $interval) - $min;
    $current->modify($change > 0 ? "+$change minutes" : "$change minutes");
    $newTime = explode(' ', $current->format('Y m d H i a'));
    list($year, $month, $day, $hour, $min, $meridian) = $newTime;
}


I honestly have no idea what the intended purpose of this is, but it appears that if both $interval and $min are set, it overwrites the default values for $hour and $min with the assumption (at $current->setTime($hour, $min)) that the provided values are in a 24-hour format. Since I'm using a 12-hour format, $meridian becomes 'am' for any value less than 12.

Am I using the helper incorrectly, or is this an error in the core? It seems like $current->setTime($hour, $min); should add 12 to $hour if $timeFormat == 12 to avoid this.

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments: