How to get a hasMany dropdown/select tag in cakephp

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.