Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony: use of query builder in a Form

I have a form that I am building using the FormBuilder:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('rosters',   'entity',   array(
            'class' => 'ReliefAppsPlatformBundle:Roster',
            'property' => 'display',
            'query_builder' => function(RosterRepository $r) use ($user) {
                return $r->createQueryBuilder('r')
                    ->leftJoin('r.members', 'm')
                    ->addSelect('m')
                    ->where('(m.rights = :adminRight or m.rights = :managerRight) and m.user = :user')
                    ->setParameter('adminRight', RosterMember::ADMIN_LEVEL)
                    ->setParameter('managerRight', RosterMember::MANAGER_LEVEL)
                    ->setParameter('user', $user);
            },
            'required' => true,
            'expanded' => true,
            'multiple' => true
        ))
        ->add('save', 'submit')
    ;
}

As you can see I my QueryBuilder I use $user (the current user) as a parameter. My controler looks like that:

public function createAction(Request $request, Event $event)
{
    $alert = new RosterEvent;
    $alert->setEvent($event);

    $user = $this->getUser();
    $form = $this->createForm(new RosterEventType(), $alert, $user);
    $form->handleRequest($request);
    if ($form->isValid()) { ....

My issue is that I need to pass the $user to the formbiulder. But I get "Catchable Fatal Error: Argument 3 passed to Symfony\Bundle\FrameworkBundle\Controller\Controller::createForm() must be of the type array, object given,..." I know the problem is how I pass $user from the controller to the formbuilder. But I have no clue how to do that. Any ideas?

like image 702
Raphael_b Avatar asked Jul 15 '15 13:07

Raphael_b


Video Answer


1 Answers

As mentioned in the documentation, the third parameter ($options = array()) of method createForm need an array and not a object.

This line is wrong

$form = $this->createForm(new RosterEventType(), $alert, $user);

The $options parameter can be used for example like this

$form = $this->createForm(new TaskType(), $task, array(
    'action' => $this->generateUrl('target_route'),
    'method' => 'GET',
));

If you want pass a parameter to the form, you can try something like this

Controller

$form = $this->createForm(new RosterEventType($user), $alert);

Form

protected $user;

public function __construct (User $user)
{
    $this->user = $user;
}

Hope it will help.

like image 169
zilongqiu Avatar answered Oct 14 '22 04:10

zilongqiu