I have a controller named class TestController which extends some Zend_Controller_Action. Now I would like to use create an instance of TestController in TestForms (a Zend_Form). I want to populate a Zend_Form_Element_Select dynamically. Please suggest how I can do this. Thanx in advance.
-
1what is the reason behind this? you should not be doing this – Raj Mar 08 '11 at 12:14
-
@emaillenin - I would like to get the select values dynamically. – Lakshman Tirlangi Mar 08 '11 at 12:19
-
can you post the source code of TestController? – Raj Mar 08 '11 at 12:23
-
$markets = UserModel::getInstance()->parseToSelectBox($this->getUser()->getMarkets(), 'market_id', 'market_name'); getUser() is a method of Controller, I would like to call that method in Form. – Lakshman Tirlangi Mar 08 '11 at 12:24
-
1that is completely wrong to call action's controller form a FORM class , there is some misunderstanding ... – tawfekov Mar 08 '11 at 12:38
-
1access your data from the database using Model – Raj Mar 08 '11 at 12:58
2 Answers
Where are you instantiating the form - is it in the controller? Instead of having the form call an action on the controller to dynamically get the values, you should look at setting the values on the form after it has been instantiated.
A quick and dirty way of doing that would be to grab the values in the controller and assign it to the element via:
$values = $db->query('query');
$element = $form->getElement('dynamicSelect');
$element->setValue($values);
Of course having DB queries to a table in your controller isn't exactly best practice... Per philistyne's suggestion, I use a a form builder class to build forms dynamically from my models. I have mappers for each model, and I pass in the mapper to the form builder class so it can dynamically populate my select elements.

- 168
- 5
A couple of things to try (passing a controller into a form or instantiating from within one is not recommended):
- Use a model to access the dynamic values you want to put into your Zend_Form_Element_Select.
- If the form is complex, create a form builder class to take care of, and separate out, the heavy lifting of the form construction.
- Create customised form elements by extending from Zend_Form_Element_(Radio, Select, etc etc) if you feel you need very fine control over the form element's construction/behaviour/appearance, but wish to be able to reuse that element elsewhere.

- 652
- 3
- 7