Search code examples
formssymfony

Symfony: parameter passed to form stay to default


with up to date Symfony, I have a custom Form, where a field is made on entity according a doctrine request. To construct this request it needs a parameter id passed by the controller, with option 'postedBy'

class StudyDecomposedType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            
            ->add('subjects', EntityType::class,[
                'class' => Subject::class,
                'choice_label' => 'identifier',
                'required' => false,
                'multiple' => true,
                'query_builder' => function (EntityRepository $er) use ($options): QueryBuilder {
                    return $er->createQueryBuilder('a')
                        ->leftJoin("a.studies", "s")
                        ->leftJoin(Studyaccess::class, 'sa', 'WITH', 's=sa.study')
                        ->where('(sa.user = :userid AND (sa.r = 1 OR sa.w = 1)) OR (a.owner= :userid)')
                        ->setParameter('userid', $options['postedBy']);
                        
                        
                },
                ])
            ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            
                'postedBy' => 0,
            

        ]);

        $resolver->setAllowedTypes('postedBy', 'int');
        
    }

In my controller, I make the form like this:

$form = $this->createForm(StudyDecomposedType::class, 
                   $options= ['postedBy' => $this->getUser()->getId(),] 
        );

But whatever the value I put into options, the value in the request is the one I put in default (here 0).

Does somebody could help me, I'm totally lost

The parameter userid should be the one given through the call to $options from crontroller, but the value never change. I verified the id in the controller, I looked the sql that is generated and the userid is always at its default value


Solution

  • The createForm() method expects the options as the 3rd parameter, but you sent them as the 2nd one which is used to send the data to populate the form fields.

    Fix the order by passing null as the second parameter (this is the actual default value):

    $form = $this->createForm(StudyDecomposedType::class, null, [
        'postedBy' => $this->getUser()->getId(),
    ]);
    

    If you're using PHP 8+ you can use named arguments:

    $form = $this->createForm(StudyDecomposedType::class, options: [
        'postedBy' => $this->getUser()->getId(),
    ]);