Quantcast
Channel: Insane in the Main Frame
Viewing all articles
Browse latest Browse all 310

group_by in formbuilder: creating optgroups in dropdown

$
0
0

I had 2 entities, “Category” and “DetailCategory”, with every DetailCategory having one Category. To make it easier in a form to select the right DetailCategory (which can have the same name in different categories), I wanted a dropdown with the categories as optgroups. I found out there is something called group_by and I tried the following:

  1. $form = $this->createFormBuilder()
  2. ->add('detailCategories', 'entity', array('label' => 'Kategorien', 'multiple' => true, 'class' => 'Package\Bundle\Entity\DetailCategory', 'group_by' => 'category', 'property' => 'name'))
  3. ->getForm();

But Symfony reacted with throwing this error:

  1. Warning: Illegal offset type in isset or empty

It seems that Symfony can’t handle “category”, since it is an entity. So I found this helpful entry on Stackoverflow and added the following function to my DetailCategory entity:

  1. public function getCategoryName(){
  2. if (null === $this->getCategory()) {
  3. return null;
  4. }
  5. if (null === $this->getCategory()->getName()) {
  6. return null;
  7. }
  8. return $this->getCategory()->getName();
  9. }

And then I changed the group_by in my form accordingly:

  1. 'group_by' => 'categoryName'

And then it worked!


Viewing all articles
Browse latest Browse all 310

Trending Articles