What is the best way to populate a select element that is part of Zend_Form?
I've used populate() to fill in various form element values but the select statements do not get populated.
My solution, which works but I suspect is not ideal, is as follows: In the init() method of MyForm (which extends Zend_Form) I make a database call and get the needed data.
$opt = Zend_Registry::get('dbAdapter');
$sql = 'SELECT DISTINCT foo FROM bar';
$res = $opt->fetchAll($sql);
$flat = $this->flattenArray($res); //this flattens the array and sets the keys to equal the values
At this point I pass $flat
to the multioptions value of the correct select element. Then, when the controller gets the form for a view, if the form needs to be populated I call populate on it and everything appears properly populated.
Some problems I see: First I have this database call in the form's init() method so it gets called every time the form is used. Second, I have a databse connection opened to populate the select element then I do a second connection to use populate.
What is a better way to do all of this? I'd like to do one database connection and use populate to fill in everything and do it all from within my controller rather than split it between the extended form class and the controller. Is this the best approach? This is my bespoke solution and it works but I KNOW it is far from ideal
(BTW, as someone who works alone and in an isolated location being able to ask stackoverflow a question like this, as if I were grabbing a colleague to ask a question, is so very useful to me... thanks)