30/08/08

2

Populate a Zend_Form select with database returned data

The code speaks for itself:

$category = new Zend_Form_Element_Select('category');
$category->setLabel('Category')
         ->setRequired(true);
 
$table = new Category();
foreach ($table->fetchAll() as $c) {
    $category->addMultiOption($c->id, $c->name);
}

“By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a false value to the registerInArrayValidator configuration key.”
Zend framework Manual.

If you want to order the way the categories are displayed you could do this in your model.

The database table:

CREATE TABLE IF NOT EXISTS `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) collate utf8_unicode_ci NOT NULL,
  `order` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;
 
INSERT INTO `category` (`id`, `name`, `order`) VALUES
(1, 'Category Three Order 3rd', 3),
(2, 'Category One Order 1st', 1),
(3, 'Category Two Order 2nd', 2);

The model:

< ?php
/** Zend_Db_Table_Abstract */
require_once 'Zend/Db/Table/Abstract.php';
 
class Category extends Zend_Db_Table_Abstract
{
    protected $_name = 'category';
 
    public function findForSelect()
    {
    	$select = $this->select();
    	$select->order('order');
    	return $this->fetchAll($select);
    }
}

Populate the select:

$category = new Zend_Form_Element_Select('category');
$category->setLabel('Category')
         ->setRequired(true);
 
$table = new Category();
foreach ($table->findForSelect() as $c) {
    $category->addMultiOption($c->id, $c->name);
}