Zend Framework 2:使用 formelementmanager 将变量 ("options") 传递给表单

Zend Framework 2: passing variables ("options") to form using formelementmanager

我需要根据某些选项以编程方式更改表单的行为。比方说,我正在显示一个包含一些用户信息的表单。

当且仅当用户尚未收到激活邮件时,我需要显示一个复选框,"send mail"。以前,对于 ZF1,我曾经做过类似

的事情
$form = new MyForm(array("displaySendMail" => true))

反过来,它作为一个选项被接收,并且允许这样做

class MyForm extends Zend_Form {

    protected $displaySendMail;

    [...]

    public function setDisplaySendMail($displaySendMail)
    {
        $this->displaySendMail = $displaySendMail;
    }


    public function init() {
        [....]
        if($this->displaySendMail)
        {
            $displaySendMail  new Zend_Form_Element_Checkbox("sendmail");
            $displaySendMail
                   ->setRequired(true)
                   ->setLabel("Send Activation Mail");
        }
    }

这如何使用 Zend Framework 2 完成?我发现的所有东西都是关于管理依赖关系的(类),除了这个 SO 问题:ZF2 How to pass a variable to a form 最后,它依赖于传递依赖项。也许 Jean Paul Rumeau 的最后一条评论可以提供解决方案,但我无法让它发挥作用。 谢谢 A.

@AlexP,感谢您的支持。我已经使用了 FormElementManager,所以它应该很简单。如果我理解正确,我应该只在我的 SomeForm 构造函数中检索这些选项,不是吗?

[in Module.php]

'Application\SomeForm' => function($sm)
           {
                $form = new SomeForm();
                $form->setServiceManager($sm);
                return $form;
            },

在 SomeForm.php

class SomeForm extends Form implements ServiceManagerAwareInterface
{
    protected $sm;

    public function __construct($name, $options) {
         [here i have options?]
         parent::__construct($name, $options);
    }
 }

我试过了,但没有用,我会再试一次,仔细检查所有内容。

使用插件管理器(classes 扩展 Zend\ServiceManager\AbstractPluginManager),您可以提供 'creation options' 数组作为第二个参数。

$formElementManager = $serviceManager->get('FormElementManager');
$form = $formElementManager->get('SomeForm', array('foo' => 'bar')); 

重要的是您如何向管理器注册服务。 'invokable' 服务会将选项数组传递到所请求的 服务的 构造函数中,但是 'factories' (必须是工厂 class 名称的字符串) 将在其构造函数中获取选项。

编辑

您已经使用匿名函数注册了您的服务,这意味着这不会为您工作。而是使用工厂 class.

// Module.php
public function getFormElementConfig()
{
    return array(
        'factories' => array(
            'Application\SomeForm' => 'Application\SomeFormFactory',
        ),
    );
}

然后是 factory 会将选项注入到它的构造函数中(如果您考虑一下,这是有道理的)。

namespace Application;

use Application\SomeForm;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;

class SomeFormFactory implements FactoryInterface
{
    protected $options = array();

    public function __construct(array $options = array())
    {
        $this->options = $options;
    }

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new SomeForm('some_form', $this->options);
    }
}

或者,您可以通过将其注册为 'invokeable' 服务来直接注入您请求的服务 (SomeForm);显然这将取决于服务需要什么依赖项。