douzhi2012 2008-12-19 23:07
浏览 8

使用Zend_Form填充数据库中的选择

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 multi-options 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 database 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条回答 默认 最新

  • dqftyn1717 2008-12-20 06:56
    关注

    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.
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器