简体   繁体   English

如何将参数从控制器传递到Zend_Form?

[英]How to pass params from controller to Zend_Form?

I know this question is already answered here . 我知道这个问题已经在这里回答 But this doesnt work for me. 但这对我不起作用。 The Form is generated by using the PluginLoader: 该表单是通过使用PluginLoader生成的:

$formClass = Zend_Registry::get('formloader')->load('Payment');
$form = new $formClass(array('someval' => $my_arr));

Payment.php: Payment.php:

class Form_Payment extends Zend_Form
{

   protected $_someval = array();

   public function init()
   {
      $this->setAction('payment/save');
      //....
      $this->addElement('multiCheckbox', 'store_id', array('label' => 'Someval:', 'required' => true, 'multiOptions' => $this->getSomeval()))
   }

   public function setSomeval($someval) {
      $this->_someval = $someval;
   }

   public function getSomeval() {
      return $this->_someval;
   }
}

As I can see the load method only returns the class name, so new $formClass(); 如我所见,load方法仅返回类名,因此new $formClass(); is equal new Form_Payment() but why this isn't accept params? 等于new Form_Payment()但是为什么不接受params?

Ok I found a way by myself. 好吧,我自己找到了一条路。 I was looking for a way to inject some params while my Zend_Form was initialised. 我正在寻找一种在初始化Zend_Form时注入一些参数的方法。 It seems the only way for this is to pass the params to the constructor - which is executed before the init method. 似乎唯一的方法是将参数传递给构造函数-该构造函数在init方法之前执行。

class Form_Payment extends Zend_Form
{

   private $_someval;

   public function __construct(array $params = array())
   {
       $this->_someval = $params['someval'];
       parent::__construct();
   }

   public function init()
   {
      $this->setAction('payment/save');
      //....
      $this->addElement('multiCheckbox', 'store_id', 
         array('label' => 'Someval:', 
               'required' => true, 
               'multiOptions' => $this->_someval // passed params now available
         )) 
   }

}

You can add custom function to your form class like 您可以向表单类添加自定义函数,例如

class Form_Payment extends Zend_Form
{
     public function init()
     {
          $this->setAction('payment/save');
          // and so on
     }

     public function doSome()
     {
          $this->setAction('other/action');
     }
}

and call it after instanciating form in controller 并在控制器中实例化表格后调用它

$form = new $formClass();
$form->doSome();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM