group_by in formbuilder: creating optgroups in dropdown

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:

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

But Symfony reacted with throwing this error:

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:

public function getCategoryName(){
    if (null === $this->getCategory()) {
        return null;
    }
    if (null === $this->getCategory()->getName()) {
        return null;
    }
    return $this->getCategory()->getName();
}

And then I changed the group_by in my form accordingly:

'group_by' => 'categoryName'

And then it worked!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.