从Symfony2中的事件订阅者访问路由参数

时间:2013-02-21 17:03:04

标签: symfony

我已在Symfony 2.0项目中设置了一个事件订阅者,该项目由表单类型用于确定是否包含字段,如讨论here

然而,为了确定是否包含,我想将实体值与路由参数进行比较。

我知道通过讨论here的类型传递变量,但我更愿意直接从订阅者访问。

我的表格类型:

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Odst\Bundle\DyfieldBundle\Form\EventListener\DyfieldFilterSubscriber;

class DyStringFieldType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $subscriber = new DyfieldFilterSubscriber($builder->getFormFactory());
        $builder->addEventSubscriber($subscriber);
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Odst\Bundle\DyfieldBundle\Entity\DyStringField',
        );
    }

    public function getName()
    {
        return 'dyStringField';
    }
}

我的活动订阅者:

use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
use Odst\Bundle\DyfieldBundle\Form\Type\DyStringFieldType;

class DyfieldFilterSubscriber implements EventSubscriberInterface
{
    private $factory;

    public function __construct(FormFactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(DataEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        if (null === $data) {
            return;
        }

        $fieldPageNameId = $data->getModel()->getDyFieldSet()->getDyFieldPage()->getNameId();
        // This doesn't work, but this is where I need to get the parameter
        $pageNameId = $this->get('request')->get('pageNameId');

        if ($pageNameId == $fieldPageNameId) {
            $form->add($this->factory->createNamed('text', 'value'));
        }
    }
}

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您可以将DyfieldFilterSubscriber作为服务并在构造函数或setter中注入Request。

编辑:

表格类型

public function __construct(DyfieldFilterSubscriber $event)
{
$this->event = $event;
}

Dy字段过滤器订户

public function __construct(Request $request)
{
    $this->request = $request;
}

public function setFormFactory(FormFactoryInterface $formFactory)
{
    $this->formFactory = $formFactory;
}

服务:

services:
    your_form_type:
    class:     FQCN\To\Your\FormType
    arguments: [@dy_field_filer_subscriber]

    dy_field_filer_subscriber:
        class:     FQCN\To\Your\Class
        arguments: [@request]

最好的关注