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

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.

Comments

  1. It’s quite old trick. In fact there is not explanation how to do it.
    I figured this through reading the code of the Form helper.

    🙂

  2. I can’t remember where I found it. I baked a couple of views and I was wondering how to do it. And as with everything else I’ve found I cake, I kept thinking: “This can’t be that hard”…

    And it wasn’t, just hidden 😀

  3. Deprecated though with cakePHP 1.2

  4. Thank u dude!
    I am new to Cake..was Baking some examples..was thinkg of this..and i got it..

Trackbacks

  1. […] Cute CakePHP Trick of the Day – GenerateList Empty Slot In List | Web Development 2.0: Web Design, C… ? select ??????????????????????????????????????????????? […]