Reputation: 851
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?
Upvotes: 0
Views: 1970
Reputation: 8161
To address the second part of your question: "what is the point of including it in the createForm
call ?"
When you pass an object as the second argument to createFormBuilder
you are passing the initial data for the form. Symfony will try to find properties (or getters/setters) that match the form field name in the object and assign its value to the field. Then, on submission, it'll update your model accordingly.
You'd tipically pass the same type of object as the form's data_class
, so in your case that would be an OrganizationCourse
. You could do something like the following:
$organizationCourse = new OrganizationCourse();
$organizationCourse->setOrganization($user->getOrganization());
$form = $this->createForm(OrganizationCourseType::class, $organizationCourse);
You could select many Courses
and assign them to the Organization
.
However, this doesn't look like your use case, since OrganizationCourse
looks like a relation rather than an entity, so refer to @ehimel's answer.
Upvotes: 2
Reputation: 1391
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']);
}
Upvotes: 1