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.

Related Posts