ZF2,将变量从控制器传递给自定义元素 [英] ZF2, pass variable to custom element from controller

查看:25
本文介绍了ZF2,将变量从控制器传递给自定义元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ZF2 中,我有一个自定义表单元素工厂.它创建一个自定义 MultiCheckbox 并填充来自数据库查询的复选框值和标签.

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;
    }
}

我的问题如下.方法 findDescriptions($id) 取决于我可以从路由中获取的 $id.但是当我以这样的形式使用 MyMultiCheckbox 时:

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

我不知道如何将 $id 传递到 MyMultiCheckbox.

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

有人可以帮助pleeeeeeeeeeease吗?

Could anyone help pleeeeeeeeeease?

推荐答案

您可以通过工厂内的路由匹配"实例获取 ID.

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);

这篇关于ZF2,将变量从控制器传递给自定义元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆