doucan8246326 2011-01-20 12:56
浏览 6
已采纳

通过控制器将值传递给Zend_Form?

I have this contact form with a selectbox, where the values on the select box, depend on the user_id. So these values are selected from the DB and I need the user_id in my form.

What I tried is giving my form a public user_id; datamember, so that when I create a form I can do this:

 $form = new My_Form();
 $form->user_id = $theUserId;

Maybe I'm missing something, but I just can't get this to work. $theUserId does have a value in my Controller, but not in my form (Whenever I do $this->user_id in my form I get: Invalid parameter number: no parameters were bound)

Any ideas how I should do this?

  • 写回答

3条回答 默认 最新

  • drz49609 2011-01-20 18:37
    关注

    You need to move the sql query out of the forms init() method which gets called by the constructor (and before you get chance to set the user id). if the results of the sql query are only needed at render time (rather than at validation time) then you might override the forms render() method, do your sql query there and then call parent::render()

    
    /* My Form */
    
    public function render($view = null)
    {
        /* SQL here */
    
        return parent::render($view);
    }
    

    EDIT:

    Ok, here's what I would do:

    
    class My_Form extends Zend_Form
    {
        private $_userId = null;
    
        /* Getter and Setter for user id here */
    
        public function init()
        {
            ...
            $this->createElement('Select', 'nameOfTheSelectElem',
                array(
                    /* Don't add the multiOptions here */
                )
            );
        }
    
        private function _addMultiOptionsForMySelectElem()
        {
            /* SQL Query here */
            $this->nameOfTheSelectElem->setMultiOptions($resultsOfTheSQLQuery);
        }
    
        public function render($view = null)
        {
            $this->_addMultiOptionsForMySelectElem();
    
            return parent::render($view);
        }
    
        public function isValid($data)
        {
            $this->_addMultiOptionsForMySelectElem();
    
            return parent::isValid($data);
        }
    }
    
    

    So in the init method you can create the element, but don't add the options to the element at this point. Create a private method to do the sql query and add the options to the select element and then call the private method from the render method and the isValid method. Hope that's clearer now. Is it?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站