30/08/08

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);
}

Comments | RSS

#1
tomasr said

Hi, could you advice me with somenting?
I have two select boxes in zend_form writern and I want filled second select box during contain of first select box, most rather by jquery.
But I can’t integreate this feature to zend framework.

Sorry for my english.
Thank you.

#3
kartieka said

sorry if this is a stupid question..
what must i put in my view to display the drop down..
plz give some idea..

#4
Gerard Roche said

sorry about the late reply, i’ve been awful busy and have only now logged in to post and found some comments.

Rob Allen posted a very good tutorial on Zend_Form, http://akrabat.com/2008/02/21/simple-zend_form-example/

#5
Hameed said

Hi, I want to display the select options like below.

category1
item1
item2
category2
item3
item4

how do i add space in front of sub items

I tried like this

$category->addMultiOption($c->id,’ ‘.$c->name);

$category->addMultiOption($c->id,’   ’.$c->name);

but not working.

also i want to specify different color for category and item through css class.

Please help me. Thanks.

Leave a Reply