ZF2 从数据库中动态添加元素到表单

ZF2 add elemets to form on the fly from database

在 ZF2 中,我从控制器工厂得到这样的表格:

class SomeControllerFactory implements FactoryInterface
{
    public function CreateService(SeviceLocatorInterface $serviceLocator)
    {
        $realServiceLocator   = $serviceLocator->getServiceLocator();
        // other things from service manager
        $registrationForm = $realServiceLocator->get('FormElementManager')
            ->get('Path\To\My\Form\RegistrationForm');
    }
    return new SomeController(
        // controller dependencies, including $registrationForm
    );
}

RegistrationForm中,我有MultiCheckBox

    $this->add([
        'type' => 'Zend\Form\Element\MultiCheckBox',
        'name' => 'partyRoleIds',
        'options' => [
            'label' => 'Отношение',
            'value_options' => [
                [
                    'value' => '1',
                    'label' => 'client',
                ],
                [
                    'value' => '2',
                    'label' => 'prospect'],
                [
                    'value' => '6',
                    'label' => 'contractor',
                ],
            ],
        ],
    ]);

我想从 returns 像 [1 => 'client', 2 => 'prospect'...] 这样的数组的数据库查询中填充 value_options。填充不是问题,但我不知道如何将此数组作为依赖项传递到 RegistrationForm 中,因为在调用 $registrationForm = $realServiceLocator->get('FormElementManager')->get('Path\To\My\Form\RegistrationForm'); 中,我没有任何地方可以添加依赖项。

我该怎么做?

PS:重写了问题,请原谅我开头的简洁。

在表单 类 中添加方法 :

public function setValueOptions($element, array $values_options)
{
    $e = $this->get($element);
    $e->setValueOptions($values_options);
    return $this;
}

在你的控制器中,如果你的表单是 $registrationForm 你写:

$registrationForm->setValueOptions('partyRoleIds', $valueOptions);

其中 $valueOptions 是一个类似于您的示例的数组。