Cute CakePHP Trick of the Day – GenerateList Empty Slot In List

Page content

List

With this post I'm introducing a new segment to this blog: Cute CakePHP Trick of the Day.

This is basically going to be a learn as I learn sort of thing. There are always a bunch of little things that I want to do in CakePHP, but just haven't figured out. So every time I stumble onto something, I'll let you guys in on it.

I love the GenerateList() function. This is generally used when you have models with associations with other models. The GenerateList function is often used in these cases to populate a drop down list or a multiple select list. A typical example is a state drop down on an address form.

One problem that I have with this implementation is that it always produces a complete list and there is no empty slot. There is nothing to say that I don't want to associate anything for this entry. On a drop down list, it's impossible not to select an element. On a multiple selection list, even if the user holds CTRL and clicks to unselect the current entry, CakePHP ignores this entry.

Here's the fix. Assuming in your controller you have something like:

$this->;State->generateList();

and in the view:

echo form->input(state_id);

Simply modify the view to give:

echo form->input(state_id, array('empty' => '--'));

This will give you an entry up at the top that the user can select, which signifies empty with the text “-". Change the text to anything you like and you'll have the desired effect.