Population Selects from database using Zend_Form

What is the best way to populate a select element that is part of Zend_Form?

I used populate()

to fill in various values ​​on a form element, but the select statements are not populating.

My solution, which works, but I suspect it's not perfect, looks like this:

In the method init()

MyForm

(which continues Zend_Form

) I make a call to the database and get the data I need.

$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 am passing $flat

the multi-options value to the correct select element. Then, when the controller receives the form to submit, if the form needs to be filled, I call it and everything appears to be filled out correctly.

Some problems I see: first I have this database query in a view init()

, so it gets called every time the form is used. Second, I have a database connection open to populate the select element, and then I use a second connection to use the fill.

What's the best way to do all of this? I would like to make one database connection and use fill to fill everything and do it all from my controller, not 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's far from perfect.

(BTW, since someone who works alone and in an isolated location might ask stackoverflow a question like this, as if I'm grabbing a colleague to ask a question, very helpful to me ... thanks)

+1


source to share


1 answer


I'm not 100% sure what you're after. I am interpreting this that the SQL call in your example is done multiple times to view the same page and you don't like that?

You can cache content for



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


source







All Articles