Zend Framework: Populate Select with DB results

After a lot of struggling and web searching I finally found out how to do this. And since I didn’t really find someone who had the same problem as me, I thought I should write a small tutorial on this topic. My problem: I had a form (BlogForm.php) where I initialized the form for my blog entries. In this form I have a selection box for selecting categories. The problem was, how could I populate this selection box with database results?

// zend_blog_category.sql
CREATE TABLE IF NOT EXISTS `zend_blog_category` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(128) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`cat_id`)
);

Form Snippet:

// forms/BlogForm.php
...
// add an category selection box
$this->addElement('select', 'cat_id', array(
		  'label'	 => 'Category',
		  'required'	 => true,
		  ));
...

The model which basically just fetches everything from the category table, and puts it in an array, sorted by $order:

// models/Category.php
public function fetchEntries($order)
{
	return $this->fetchAll(null,$order)->toArray();
}

Now lets take a look at our admin BlogController where all this comes together:

// controllers/BlogController
public function thisisourAction()
{
	...
	$form->populate($data);
	...
}
 
protected function _getForm($action)
{
	require_once APPLICATION_PATH . '/forms/BlogForm.php';
    	require_once APPLICATION_PATH . '/models/Category.php';
    	$table = new models_Category();
        $form = new forms_BlogForm();
        $form->setAction($this->_helper->url($action));
        foreach($table->fetchEntries('cat_id') as $c)
        {
        	$form->getElement('cat_id')
		->addMultiOptions(array(
			$c['cat_id'] => $c['cat_name']
			));
        }
        return $form;
}

Hope this was helpful to whomever might be looking for a good answer about this subject! Good luck.

About Torstein Skulbru

23 year old, Bachelor ICT(Information and Communication Technology) student at University of Bergen (NO)