我对如何在 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/