Unexpected behavior with drop-down option order using minYear, maxYear in CakePHP

Main Thread 1 min read

I noticed something interesting when testing a checkout form today build in CakePHP. The options for the drop-down were in descending order. The options were for the credit card expiration date field. The range was set with minYear and maxYear attributes.

The code in my view (CakePHP version 1.3.7).

1echo $this->Form->input('cc_expires', [
2 'type' => 'date',
3 'label' => 'Expiration Date',
4 'dateFormat' => 'MY',
5 'empty' => true,
6 'separator' => ' ',
7 'minYear' => date('Y'),
8 'maxYear' => date('Y', strtotime('+7 years'))
9]);

Although the options range is correct, this seemed unintuitive. In addition, I felt it was slightly poor usability. So I wanted to fix the order.

CakePHP default option order
CakePHP default option order

I dug around in The Book. Nothing. I was about to submit a ticket. But before I do, I typically check my version and the core. Upon searching for minYear I found the function in question – year(). Apparently an undocumented attribute exists – orderYear. After adding 'orderYear' => 'asc' to the options array I got the desired output.

Two notes here. First, CakePHP has many undocumented features. It never hurts to dig around the core. Second, the orderYear attribute is completely unnecessary in this case. In fact, it is only used for the *year* drop-down. It could be easily determined from comparing minYear and maxYear. In this case, minYear is 2012 which is less than maxYear is 2019. Display in ascending order.

Control option order using orderYear for year in CakePHP
CakePHP option order with orderYear

Maybe orderYear has uses. But today it wasted my time.</rant>

Find this interesting? Let's continue the conversation on Twitter.