Doo*_*roo 3 symfony symfony-2.1
我对如何访问Symfony 2中的当前用户感到有点困惑.目前我正在尝试根据当前用户的ROLES显示表单的变体(AbstractType).
Gremo已经回答了类似的问题:Access当前在EntityRepository中登录用户
我的问题是:在没有使用JMSDiExtraBundle的情况下,是否有一种Symfony 2本地方式来访问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';
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我正在寻找当前登录的用户(security.context)
Don*_*sto 14
进入你的控制器,做这样的事情
$form = $this->createForm(new CommentType($this->get('security.context')
->isGranted('ROLE_ADMIN')), $comment);
Run Code Online (Sandbox Code Playgroud)
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(....);
}
Run Code Online (Sandbox Code Playgroud)
JMSDiExtraBundle提供(以及其他)注释和快捷方式,以便定义服务,例如表单类型和学说监听器,这只是常规服务,但具有特定标签.如果我没记错,捆绑包包含在标准的Symfony 2.1版本中,为什么不使用呢?
无论如何注入用户"旧方法",使用构造函数注入例如:
class Comment extends AbstractType
{
private $context;
public function __construct(SecurityContext $context)
{
$this->context = $context;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$loggedUser = $this->context->getToken()->getUser();
/* ... */
}
}
Run Code Online (Sandbox Code Playgroud)
并将其定义为带有form.type标记的服务:
<service id="form.type.comment" class="Acme\DemoBundle\Form\Comment">
<argument type="service" id="security.context" />
<tag name="form.type" alias="comment" />
</service>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10019 次 |
| 最近记录: |