Reputation: 851
I would like to access the entities submitted by a form without having to use a nested for loop. Currently, in order to access the entity objects I am doing the following:
$courses = $form->getData();
foreach ($courses as $course) {
foreach ($course as $c) {
//do logic on entity $c
}
}
Form builder class:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('courses', EntityType::class, [
'class' => Course::class,
'choice_label' => 'name',
'multiple' => true,
'expanded' => true,
'required' => false,
'query_builder' => function (EntityRepository $er) use ($organization) {
return $er->createQueryBuilder('course')
->orderBy('course.semester', 'ASC');
},
]);
}
How can I structure the form such that the entities would be accessible with a single for loop?
Upvotes: 0
Views: 593
Reputation: 8171
Your call to getData()
is returning all form fields, but since you seem to have only one, it is working as "you expect" but just by accident. If you decided to add more fields, a user
field for instance, at some point the $course
variable will hold a User
entity. It'll be more clear if you rewrite this as $fieldData = $form->getData()
, and now you can think of it as an array keyed by fieldName
.
You should be able to get just the Course
collection (the specific field) by using:
$courses = $form->get('courses')->getData();
// Or using PropertyAccess: $form['courses']->getData()
foreach ($courses as $course) {
// ...
}
Upvotes: 1