Format Month Names for the Cake FormHelper

July 23, 2008 :: No Comments

I was scratching my head trying to figure out how to modify the month names that the Cake FormHelper used when generating it's select box. At first I just hacked the Core, but lately I have been making it a rule to never modify the Core. Thank God Cake was built with the flexibility to not have to.

My next idea was (suggested by mrConfused on the #cakephp irc channel) to extend the FormHelper with my own month() method. That just rubbed me the wrong way. Too much code duplication.

Enter Localization....

While poking around in the API, I noticed that the __generateOptions method that Cake used to create the month names was wrapping the month names like this:

 
if ($options['monthNames']) {
    $data['01'] = __('January', true);
    $data['02'] = __('February', true);
    $data['03'] = __('March', true);
    $data['04'] = __('April', true);
    $data['05'] = __('May', true);
    $data['06'] = __('June', true);
    $data['07'] = __('July', true);
    $data['08'] = __('August', true);
    $data['09'] = __('September', true);
    $data['10'] = __('October', true);
    $data['11'] = __('November', true);
    $data['12'] = __('December', true);
}
 

Well that __() method they are wrapped in is where Localization came into play.

To read up more on how Localization works in Cake. Check out the Cookbook article on it here: http://book.cakephp.org/view/161/localization-internationalizat

So I put this in my controller:

 
/**
 * Before Filter
 *
 * @return void
 * @author Adam Duro
 **/
    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow('add', 'thanks');
 
        /* This is where the Localization stuff is loaded */
        if (!class_exists('L10n')) {
            App::import('Core','L10n');
        }
        $this->L10n = new L10n();
        $this->L10n->get('eng');
        Configure::write('Config.language', "eng");
    }
 

And then all I had to do was put the following in app/locale/eng/LC_MESSAGES/default.po

 
msgid   "January"
msgstr  "Jan"
msgid   "February"
msgstr  "Feb"
msgid   "March"
msgstr  "Mar"
msgid   "April"
msgstr  "Apr"
msgid   "May"
msgstr  "May"
msgid   "June"
msgstr  "Jun"
msgid   "July"
msgstr  "Jul"
msgid   "August"
msgstr  "Aug"
msgid   "September"
msgstr  "Sep"
msgid   "October"
msgstr  "Oct"
msgid   "November"
msgstr  "Nov"
msgid   "December"
msgstr  "Dec"
 

And voila! The select boxes are now using abbreviated month names.

NOTE: If Cake is using these Localization keys (ie. January, Febuary, etc) anywhere else in the core, and the Localization class is being used in that controller, these abbreviations will be used.

Hope that helps someone.

Share |

Comments

Leave a Comment