How to get a hasMany dropdown/select tag in cakephp

February 14th, 2009

Getting a dropdown of items a model hasMany of, should be very easy to do, but I always forget and it takes me far longer to find it than it should.

For this brief example, we’re assuming that we have an Uploads model and a FileCategory model.
Uploads belongs to FileCategory and File Category has many Uploads … get it?

class Upload extends AppModel {
   var $belongsTo = array('Client', 'FileCategory');
}
 
class FileCategory extends AppModel {
   var $hasMany = array('Upload');
}

All you need to do to is get the items for the dropdown with a find(’list’) command and then include it with a FormHelper method parameter.

If most of the actions in your controller will need this dropdown, then you might want to move it into a beforeFilter() like this

function beforeFilter(){
	$this->set('file_categories', $this->FileCategory->find('list', array('order' =>; 'name')));
}

Now, in the view where you want the dropdown to appear, you just call the FormHelper input method like this.

input('file_category_id', array('options' => $file_categories, 'label' =>; 'File Category: ', 'class' => 'short')) ?>

and there you have it.

Hope this helps someone.

Entry Filed under: cakephp

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

May 2012
S M T W T F S
« May    
 12345
6789101112
13141516171819
20212223242526
2728293031  

I recommend

Linode VPS's for Rails hosting

Heroku for mindless Rails hosting

Site 5 for shared Rails hosting and all round great service

Most Recent Posts

Categories