Symfony 以表单类型注入令牌存储 [英] Symfony Inject Token storage in form type

查看:24
本文介绍了Symfony 以表单类型注入令牌存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道在表单事件侦听器中连接的用户.所以我在我的 formType 类中注入了 token storage 并声明了服务.但它似乎不起作用.

I need to know the user connected in a form event listener. So I have injected the token storage in my formType class and have declare the service. But it does not seems to work.

我做错了吗?

class AlertType extends AbstractType
{
    private $tokenStorage;

    /**
     * @param TokenStorageInterface $tokenStorage
     */
    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class, array('label' => 'Votre adresse email'));

        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
    }

    public function onPreSetData(FormEvent $event)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        dump($user);
        die;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'FM\MailAlertBundle\Entity\Alert',
        ));
    }
}

服务声明:

 services:
        fm.mail_alert.form.alert_type:
            class: FM\MailAlertBundle\Form\AlertType
            arguments:
                - '@security.token_storage'
            tags:
                - { name: form.type }

错误信息:

类型错误:参数 1 传递给FM\MailAlertBundle\Form\AlertType::__construct() 必须实现界面Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface,没有给出

Type error: Argument 1 passed to FM\MailAlertBundle\Form\AlertType::__construct() must implement interface Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface, none given

我的目的是在用户连接时禁用字段电子邮件.

My purpose is to disable the field email if a user is connected.

推荐答案

酷.我使用 symfony 2.8 所以我不得不在我的控制器中通过 AlertType::class 更改 new AlertType 并且它起作用了;)

Cool. I use symfony 2.8 so I had to change new AlertType by AlertType::class in my controller and it worked ;)

这篇关于Symfony 以表单类型注入令牌存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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