Automagical selects or checkboxes

A quick example of some automagic goodness…

Let’s say we need to to build an “add Post” form and allow the user to pick some tags for the Post.

In our Posts controller’s add() action, we’d probably do something like this:

$this->set('tags', $this->Post->Tag->find('list', array('fields'=>array('Tag.tag'))));

Then in the view, while building the form, all we need to do is:

echo $form->input('Tag', array('multiple'=>'checkbox'));

Yep, cake will automagically recognize the $tags variable, which we set in the controller, realize that we have Post->Tag models, find the ‘Tag’ field and decide that what we really wanted to do is build a list of checkboxes from our array of $tags.

You can experiment with field names for other cases… things like ‘tags’ or ‘tag_ids’ for the field name should work as well.

  • kiran aghor

    wow… kool trick. worked for me. thanx a lot. :)

  • teknoid

    @kiran aghor

    You’re welcome ;)

  • Gary

    Another great example from you teknoid.


  • @Gary

    No problem ;)

  • Thanks a lot bro…

    I was searching for this for last three hours…..thank you for the post…

    just one update….in my application I just changed one line in views, as described by you

    1. echo $form->input(‘Tag’, array(‘multiple’=>’checkbox’));

    and it worked…no need to add/modify controller (I am using cakephp1.2)

  • @Vijai Pandey

    Cool. Glad it helped.

  • I have a HABTM association
    Table A, B which is linked via Table A_B

    $form->input(‘area_id’, array(‘class’ => ‘short’, ‘div’ => array(‘id’ => ‘area_id’, ‘class’ => ‘area_id’)));

    I ahve a standard list of Areas. How can i get a default value say “Choose Area”
    and how to validate the area field to make sure something is selected other than Choose Area.

  • @Harsha M V

    Did you check the manual about the ’empty’ key?

    I have another post regarding habtm validation, a quick search should give you some hints.

    • Yes i have seen about the emty key and checked your post about habtm validation.

      strangely its not working

      echo $form->input(‘area_id’,array(‘class’ => ‘short’, ‘div’ => array(‘id’ => ‘area_id’, ‘class’ => ‘area_id’, ’empty’ => ‘Choose Area’)));

  • @Harsha M V

    Looking at that code it seems like your ’empty’ key is in the wrong place (i.e. it’s inside the ‘div’ setting)…
    and class and id attributes have the same name?… a little quirky css :)

    • Yep it was in the wrong place. it works now :D

      abt the same name for class n ID. i still havent applied any CSS rules. its just a temp thing. i am still learning cakephp :D

  • @Harsha M V

    Cool. Glad everything worked out.

%d bloggers like this: