我认为表单订阅者的工作方式与常规事件监听器有点不同。
在您的控制器中,您正在实例化您的表单类型,即
$form = $this->createForm(new CustomerType(), $customer);
由于容器在您的控制器中可用,您可以将它直接传递给您的表单类型,即
$form = $this->createForm(new CustomerType($this->container), $customer);
在我的情况下,我需要安全上下文,所以我的实现(与你原来的 q 相似但略有不同):
在我的控制器中:
$form = $this->createForm(new CustomerType($this->get('security.context')), $customer));
在我的表单类中:
use Symfony\Component\Security\Core\SecurityContext;
class CustomerType extends AbstractType
{
protected $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function buildForm(FormBuilder $builder, array $options)
{
// Delegate responsibility for creating a particular field to EventSubscriber
$subscriber = new CustomerAddSpecialFieldSubscriber($builder->getFormFactory(), $this->securityContext);
$builder->addEventSubscriber($subscriber);
$builder->add( ... the rest of my fields ... );
}
// other standard Form functions
}
在我的表单订阅者中
use Symfony\Component\Security\Core\SecurityContext;
CustomerAddSpecialFieldSubscriber
{
private $factory;
protected $securityContext;
public function __construct(FormFactoryInterface $factory, SecurityContext $securityContext)
{
$this->factory = $factory;
$this->securityContext = $securityContext;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(DataEvent $event)
{
if (true === $this->securityContext->isGranted('ROLE_ADMIN')) {
// etc
}
}
}
希望能帮助到你。