非常简单。只需将自定义表单类型设置为服务,具体取决于安全上下文:
use Symfony\Component\Security\Core\SecurityContext;
class UserType extends AbstractType
{
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function buildForm(FormBuilder $builder, array $options)
{
// Current logged user
$user = $this->securityContext->getToken()->getUser();
// Add fields to the builder
}
public function getDefaultOptions(array $options)
{
return array(
'required' => false,
'data_class' => 'Acme\HelloBundle\Entity\User'
);
}
public function getName()
{
return 'user_type';
}
}
然后使用特殊标记将类标记为服务:form.type
services:
form.type.user:
class: Acme\HelloBundle\Form\Type\UserType
arguments: ["@security.context"]
tags:
- { name: form.type, alias: user_type }
在控制器中,不是执行 ,而是从容器中抓取服务:new UserType()
$form = $this->createForm($this->get('form.type.user'), $data);