Symfony 2 - how to pass data to formBuilder?

Viewed 50734

I'm using entity choice list in my form. I want to use only specific entities (in example: only groups that user belongs to) So, in controller, I'm getting these groups, and trying to pass them into formBuider.

Controller:

/.../
$groups = $em->getRepository('VendorMyBundle:Group')->getUserGroups($user);
$form = $this->createForm(new Message($groups), $message);
/.../

so, what now? how to use it in formBuilder? how to change this line to use passed array of groups?

->add('group','entity',array('class' => 'Vendor\MyBundle\Entity\Group', 'label'=>'Group:'))

or in the other way:

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
    ;
  }
/.../
}

so how can i get object $user to use in form builder? ($user represent current logged user)

6 Answers
Related