gpt4 book ai didi

symfony - 自适应 Symfony2 形式选择

转载 作者:行者123 更新时间:2023-12-02 05:12:24 30 4
gpt4 key购买 nike

我刚刚创建了一个表单类类型,它有一个选择类型,其中 choice_list 必须根据登录的用户角色进行更改,因此表单类类型需要访问当前用户角色,然后根据它更改 choice_list

有人能指出一种通过 Symfony2 表单模式来完成它的巧妙方法吗?

最佳答案

您需要将表单类型注册为服务并通过构造函数获取安全上下文。如果您安装了 JMSDiExtraBundle,您可以这样做:

<?php
namespace ...;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Security\Core\SecurityContextInterface;
use JMS\DiExtraBundle\Annotation\FormType;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;

/**
* @FormType
*/
class YourType extends AbstractType
{
/**
* @InjectParams({
* "securityContext" = @Inject("security.context")
* })
*
* @var SecurityContextInterface
*/
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}

/**
* @return string
*/
public function getName()
{
return 'your_type';
}
}

这样您就可以从安全上下文中获取所需的一切。

由于表单被注册为服务,因此在创建表单时使用它的名称而不是它的类:

$form = $this->createForm('your_type', /* ... */);

关于symfony - 自适应 Symfony2 形式选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15209910/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com