我在 Symfony 2.0 项目中设置了一个事件订阅者,表单类型使用它来确定是否包含一个字段,例如这里讨论的。
但是,为了确定是否包含,我想将 Entity 值与路由参数进行比较。
我知道通过此处讨论的类型传递变量,但我更愿意直接从订阅者访问。
我的表格类型:
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'));
}
}
}
非常感谢您的帮助。