symfony - 在 Symfony 2.1 抽象类型中访问当前用户

标签 symfony symfony-2.1

我对如何在 Symfony 2 中访问当前用户感到有些困惑。目前我正在尝试根据当前用户的 ROLES 显示表单的变体(AbstractType)。

Gremo 已经回答了类似的问题:Access currently logged in user in EntityRepository

我的问题是:是否有一种 Symfony 2 native 方式可以在不使用 JMSDiExtraBundle 的情况下访问我的 AbstractType 类中的用户?谢谢!

这是我当前的代码:

namespace Acme\DemoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class Comment extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        //somehow access the current user here

        $builder
            ->add('name')
            ->add('comment_text')
            ->add('comment_email')

        // Add more fields depending on user role

                ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\DemoBundle\Entity\Comment'
        ));
    }

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

编辑:我正在寻找当前登录的用户 (security.context)

最佳答案

进入你的 Controller ,做这样的事情

$form = $this->createForm(new CommentType($this->get('security.context')
                                           ->isGranted('ROLE_ADMIN')), $comment);

哪里ROLE_ADMIN是您要区分的角色。

现在,进入您的 Type你必须通过以下方式检索它
private $isGranted;

public function __construct($roleFlag)
{
  $this->isGranted = $roleFlag;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
  $builder
    ->add('name')
    ->add('comment_text')
    ->add('comment_email');

    if($this->isGranted) {
      $builder
        ->add(....)
        ->add(....)
        [....]
        ->add(....);
}

关于symfony - 在 Symfony 2.1 抽象类型中访问当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12686926/

相关文章:

Symfony2 : how to force download

php - 将动态生成的表单嵌入到另一个表单中

symfony - 如何在 SonataAdminBundle 中使用角色

symfony - 奏鸣曲管理包 : strange with labels

sockets - ClankBundle 不会触发订阅

php - Symfony2 Monolog 到电子邮件错误为什么 swiftmailer.transport.real 是不存在的服务

php - 交响乐 2.3 : CollectionRegionDoctrineCommand not found when update vendors and clear cache

Symfony 需求检查器返回 404 未找到

php - Symfony 表单集合

php - 使用 Symfony 测试数据库插入