很简单。只需根据安全上下文使您的自定义表单类型成为服务:
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);