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',
                ],
            ],
        ],
    ]);

我想从返回类似 [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是类似于示例的数组。