Dynamic Select-List in Zend_Form

| No Comments | 2 TrackBacks
Recently I decided to set up my new homepage with the Zend Framework, since it is one of the more mature frameworks and they have a consistent development of the framework, this means no bigger changes in coding style since version 1.2 or so. Other frameworks may be good as well and have maybe even more sophisticated methods for a rapid application development (RAD), but this is not to discuss here.

I started two weeks ago, mainly on the weekends to work on the tutorial from Pádraic Brady which he published on his blog "Maugrim The Reaper's Blog". The tutorial, which as announced will be revisited, can be found here.

After working through this tutorial you will be able to work on your own with the framework pretty well. One of the first problems I encountered was, that I had to use Selects in the forms to link with other components of my application respectively set a foreign key into the MySQL-Table.

Well, looking at the documentation you will find a lot of examples, but none has fit right into the coding style of the application, since the tutorial is using one of the fastest annotations possible in Zend Framework. The flexibility of the framework is maybe one aspect that may a beginner confuse a little bit.
But within a few searches I found help:
So enough material to work on. This is then what I made of it:

1. Write a little private function in the custom Form which selects all the categories and their id's:
private function _categorySelection()
{
	$table = new LinkCategories;
	// fetch all rows
	$row = $table->fetchAll(
		$table->select()->from($table, array('id', 'lcat_title'))
	);
	
	// init array
	$options = array();
	
	foreach($row as $option)
	{
		$options[$option->id] = $option->lcat_title;
	}
	
	return $options;
}

2. Call the function within the declarations of the options:

$this->addElement('select', 'category', array( 
'decorators' => $this->_standardElementDecorator, 
'label' => 'Category:',
'required' => true,
'multiOptions' => $this->_categorySelection()
 ));

This is all. The code is tested an runs under 1.7.0. It even works with the editing form, the right selections is marked when reopening respectively editing a previous saved entry.

2 TrackBacks

This article represents another solution from my work with the Zend Framework. Read More

In the first part I have explained how to use the auto increment value from MySQL to store images together with Zend Framework. Now we will see how to access the files and the stored information. Read More

Leave a comment