我在表单中使用了实体选择列表。我想仅使用特定的实体(例如:只有用户所属的群组)。
因此,在控制器中,我获取这些群组,并尝试将它们传递给formBuilder
。
控制器:
/.../
$groups = $em->getRepository('VendorMyBundle:Group')->getUserGroups($user);
$form = $this->createForm(new Message($groups), $message);
/.../
那么,现在怎么办?如何在formBuilder中使用它? 如何更改此行以使用传递的组数组?
->add('group','entity',array('class' => 'Vendor\MyBundle\Entity\Group', 'label'=>'Group:'))
或者另一种方式:
class MessageType
{
/.../
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('group','entity',
array(
'class' => 'Vendor\MyBundle\Entity\Group',
'property' => 'name',
'query_builder' => function ($repository) {
$qb = $repository->createQueryBuilder('group');
$qb->add('where', 'group.administrator = :user');
$qb->setParameter('user', $user->getId());
return $qb;
},
'label' => 'Group'
)
)
// Continue adding fields
;
}
/.../
}
如何获取对象 $user 以在表单构建器中使用?($user 表示当前登录的用户)