Search code examples
symfonyquery-builderformbuilder

Symfony2: formbuilder : dynamically modify querybuilder


I am using the formbuilder to create a form as followed:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('content',    'textarea')
        ->add('rosters',    'entity', array( 
            'class'    =>   'PlatformBundle:team',
            'property' =>   'display',
            'multiple' =>   true,
            'expanded' =>   true,
            'required' =>   true
        ))
        ->add('send',       'submit')
    ;
}

At the moment I get all "teams". I need to adapt the form to display certain teams depending of the request. I can use the query-builder inside the form builder

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('content',    'textarea')
        ->add('rosters',    'entity', array( 
            'class'    =>   'PlatformBundle:team',
            'property' =>   'display',
            'query_builder' => function(TeamRepository $t) use ($userId) {
                return $r->createQueryBuilder('t')
                    ->where('(t.user = :user')
            },
            'multiple' =>   true,
            'expanded' =>   true,
            'required' =>   true
        ))
        ->add('send',       'submit')
    ;
}

But the query changes for different questionnaire. In brief: always the same questionnaire but different teams to be listed (Am I making sense?).

Does someone has an idea how dynamically modify the querybuilder inside a formbuilder?


Solution

  • I suggest two possible alternatives.

    If the request comes from the form itself (i.e. you already submitted the form with some data and want to refine the fields) you can access the submitted data like this:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $data = $builder->getData();
        // now you can access form data
    

    If the request comes from another source, you should use the "options" parameter. First, build a new $option for the requested user:

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'user' => null,
        ));
    }
    

    Note: I set the default to null but you can set it to whatever you want.

    After that you can pass the $option where you build the form, i.e.

    // some controller
    $option = array('user' => $request->get('user');
    $teamForm = $this->createForm(new TeamType(), null, $options);
    // ...