问题
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