views:

1057

answers:

1

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)

+1  A: 

I'm not 100% sure what you're after. I interpret it that the SQL call in your example is executed multiple times for one page view, and you don't like that?

You can cache the select contents for

  • the page view with a static variable in the init function or in the class.
  • the user as a session variable.
  • all users to file or memcache with Zend_Cache, depending on how dynamic it is generated.
OIS