【发布时间】:2017-10-25 16:21:07
【问题描述】:
我想在表单事件中获取当前登录的用户,但由于某种原因我无法让它工作。
我使用服务注入 token_storage 并创建构造函数方法来获取令牌存储实例,但我在构造函数处遇到错误:
Type error: Argument 1 passed to AdminBundle\Form\EventListener\CompanyFieldSubscriber::__construct() must implement interface Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface, none given
我不确定是什么问题以及如何解决它。有人知道问题出在哪里吗?
编辑 1:
我想我发现问题出在哪里,但我找不到“好的”解决方案。我以这种方式在表单类型中调用此事件:
->addEventSubscriber(new CompanyFieldSubscriber());
问题是我没有使用“服务/依赖注入”来创建事件,并且我没有向构造函数发送任何内容。这就是我有这个错误的原因(不是 100% 肯定是诚实的)。
由于我有大约 20-30 个表单并且新表单会及时出现,我需要为每个需要用户(或 token_storage)实例的表单创建服务,并作为参数调用 token_storage 或此事件订阅者作为服务参数。
我知道,如果我将每个表单创建为服务并将所需数据作为参数传递,它会起作用,但是有没有办法“自动”处理这个,而不需要为需要在表单中进行一些用户数据交互的每个表单创建新服务活动?
编辑 2:
按照建议,我尝试更改事件订阅者构造函数,但使用不同的类名时出现相同的错误。
新代码:
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
新错误:
Type error: Argument 1 passed to AdminBundle\Form\EventListener\CompanyFieldSubscriber::__construct() must be an instance of Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage, none given
这是我正在使用的代码:
服务:
admin.form.event_listener.company:
class: AdminBundle\Form\EventListener\CompanyFieldSubscriber
arguments: ['@security.token_storage']
tags:
- { name: form.event_listener }
事件监听器:
namespace AdminBundle\Form\EventListener;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class CompanyFieldSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $user;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
$this->user = $this->tokenStorage->getToken()->getUser();
}
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::PRE_SUBMIT => 'preSubmitData',
];
}
public function preSetData(FormEvent $event)
{
$form = $event->getForm();
if (in_array("ROLE_SUPER_ADMIN", $this->user->getRoles())) {
$form->add('company', EntityType::class, [
'class' => 'AppBundle:Company',
'choice_label' => 'name'
]);
}
}
public function preSubmitData(FormEvent $event)
{
$form = $event->getForm();
$bus = $form->getData();
if (!in_array("ROLE_SUPER_ADMIN", $this->user->getRoles())) {
$bus->setCompany($this->user->getCompany());
}
}
}
【问题讨论】:
标签: php symfony listener symfony-3.2