ZF2 How to pass a variable to a form

一笑奈何 提交于 2019-12-11 01:43:53

问题


What's the easiest way to pass a variable to a form in zend framework 2?

It seems you can only send a name value to the contructor, but i need to send a few options to the form to set/fill some selectors.

Thanks!


回答1:


If you extend Form with your own class:

class MyForm extends \Zend\Form\Form

You can then pass in any variables you like via it's constructor and pass the form name to the parent Form class as such:

public function __construct($myVar, $myVar2)
{
    //do things with my vars
    $this->setVar($myVar);

    // send name to parent constructor
    parent::__construct('myFormName');
}

You might also want to consider using a Factory to inject your dependencies which can be configured for example in your Module.php:

public function getFormElementConfig()
{
    return array(
        'factories' => array(
            'MyForm' => function (ServiceManager $sm) {
                return new \MyNamespace\MyForm($sm->get('someDependancy'));
            },
        )
    );
}

This form is now available via the service locator from any service aware class:

$serviceLocator->get('FormElementManager')->get('MyForm');

With the dependencies injected via the factory.



来源:https://stackoverflow.com/questions/25674282/zf2-how-to-pass-a-variable-to-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!