ZF2, pass variable to custom element from controller

我只是一个虾纸丫 提交于 2019-12-12 02:51:40

问题


In ZF2, I have a custom form element factory. It creates a custom MultiCheckbox and fills the checkbox values and labels from a db query.

class MyMultiCheckboxFactory
{
    public function __invoke(FormElementManager $formElementManager)
    {
        $multiCheck = new \Zend\Form\Element\MultiCheckbox();

        $serviceManager = $formElementManager->getServiceLocator();
        $mapper = $serviceManager->get('Path\To\Mapper\To\Query\DB');
        $descriptions = $mapper->findDescriptions($id);

        // some processing to prepare $value_options array

        $multiCheck->setOptions([
            'label' => 'blah-blah',
            'value_options' => $value_options
        ]);

        return $multiCheck;
    }
}

My problem is as follows. The method findDescriptions($id) depends on the $id which I can get from the route. But when I use MyMultiCheckbox in the form like this:

public function init()
{
    $this->add([
        'type' => 'Path\To\MyMultiCheckbox',
        'name' => 'someName'
    ]);
}

I don't know how to pass the $id into the MyMultiCheckbox.

Could anyone help pleeeeeeeeeease?


回答1:


You can fetch the id via the 'route match' instance inside the factory.

$event = $serviceManager->get('Application')->getMvcEvent();
$id = $event->getRouteMatch()->getParam('id', false);

if (empty($id)) {
   throw new ServiceNotCreatedException('id not set!');
}

$descriptions = $mapper->findDescriptions($id);


来源:https://stackoverflow.com/questions/36107490/zf2-pass-variable-to-custom-element-from-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!