ZF2 How to pass a variable to a form

2019-07-20 01:33发布

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条回答
甜甜的少女心
2楼-- · 2019-07-20 02:01

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.

查看更多
登录 后发表回答