MainelyDesign.com Blog

Date Input Using Cakephp Form Helper

Posted on 09/09/2009 at 03:29 pm by Kevin Wentworth
Viewed 32,786 times | 3 comments

I always forget what exactly needs to happen in order for CakePHP's form helper to work with date input fields.  I'm sick of tearing through old source code and looking at the official CakePHP docementation site.  Here's how to get it to work...

Date Inputs Using the Form Helper:

  1. $current_year = date('Y');
  2. $max_year = $current_year + 2;
  3. echo $form->input('dateSelectBoxes', array('type'=>'date', 'selected'=>$unix_timestamp, 'empty'=>true, 'minYear'=>2009, 'maxYear'=>$max_year));

It's pretty simple, but just different enough from the other form helper inputs that I'm always forgetting the correct syntax.  To recap:

  • type - In order to only have the date show (and not the date AND time) specify a type of date.
  • selected - To set the value of the select boxes, use the selected key (NOT default)
    • The value for 'selected' MUST BE a unix timestamp (at least I couldn't get it to work with a mm/dd/YYYY format as of 1.2.3.8166)
  • empty - Set empty in order to have empty options at the top of the lists
  • minYear - Defines the year that you want as the minimum
  • maxYear - Define the year that you want to be the maximum (I like to calculate it based on the current year, see above)

In case you are curious as to why the dates are listed in descending order, it's a bug/feature request.  If you want to make the change now, to your CakePHP core, just follow the directions and add the following to your form helper file:

  1. $data = array_reverse($data, true);

Cheers,

-Kevin Wentworth

Bookmark and Share

Tags for Date Input Using Cakephp Form Helper

Cakephp | Web Programming | Usage | Forms

Comments for this Posting

Posted by Farhan

on 8/5/10

Thanks for sharing.
'selected'=>$unix_timestamp,
was helpfull a lot, I googled for an hour, but could not find a solution for it. Cake documentation also did not state anywhere about this.

Thanks for the help

Posted by parthi

on 23/6/10

Thanks for sharing.
It was very helpful.

Posted by M Danish

on 29/9/10

THANK YOU VERY MUCH FOR YOUR GREATEST HELP,i was really stuck in this small thing...thats gr8

www.computedsynergy.com

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design