Search code examples
phpsymfony4symfony-forms

Accessing Entity Passed to Form Builder with Symfony


I am building a form using the Symfony framework and am trying to understand how to pass an instance of an entity to the form builder.

Controller:

$organization = $user->getOrganization();
$form = $this->createForm(OrganizationCourseType::class, $organization);

OrganizationCourseType class:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('courses', EntityType::class, [
            'class' => Course::class,
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => true,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('course')
                    ->andWhere('course.organization = :organization')
                    ->setParameter('organization', $organization);
            },
        ]);
    }

However I get the error:

Notice: Undefined variable: organization

How can I access the entity (organization) within the form builder? Do I need to pass it as an option? If so what is the point of including it in the createForm call in the controller?


Solution

  • In your controller, pass the instance of your entity as a third argument to your $form definition line:

    $form = $this->createForm(OrganizationCourseType::class, null, ['organization' => $organization]);
    

    Then retrieve it in your FormType class like so:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $organization = $options['organization'];
    
        $builder->add('courses', EntityType::class, [
            'class' => Course::class,
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => true,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('course')
                    ->andWhere('course.organization = :organization')
                    ->setParameter('organization', $organization);
            },
        ]);
    }
    
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(['organization']);
    }