Reputation: 31
I have two entities with some properties:
There is a ManyToOne relation in the subcategory entity i.e. several subcategories can be connected to one category.
I would like to build a form with a dropdown listing all the subcategories, but I would like to display the name of category and subcategory, the list would look like so:
I'm thinking about creating a getter in the subcategory class that would return a concatenation of the category name and subcategory name, something like sprintf('%s - %s', $this->categoryName, $this->subcategoryName), but I can't see how I could access Category object properties using the subcategory class getter...
Any idea about the best practice to achieve this?
Thank you, JM
Upvotes: 0
Views: 3092
Reputation: 1680
You can use this method it is clear.when you have the IdCategory of Subcategory table, you access the fields Category table too
->add('idCategory', EntityType::class,array(
'data' => $options[0]['idCategory'],
'class' => 'AppBundle:subcategory',
'choice_label' => function (subcategory $subcategory) {
return $subcategory->getName() . '-' . $subcategory->getCategoryID()->getName().'-'.$subcategory->getCategoryID()->getDescription();
},
'attr' => array(
'label' => 'Category ',
'class' => 'form-control'
)
))
Upvotes: 0
Reputation: 31
I managed to do this by building the form like so:
$builder
->add('subcategoryName', EntityType::class, array(
'class' => 'AppBundle:subcategory',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->addSelect('t')
->join('u.category', 't' )
->orderBy('t.category', 'ASC')
->addOrderBy('u.subcategory', 'ASC');
},
'choice_label' => function($subcategoryname){
return $categoryname->getcategory()->getcategoryname() . " - " . $subcategoryname->getsubcategoryName();
},
'multiple' => false,
'expanded' => false,
))
I was only strugling a bit with the choice_label option.
/JM
Upvotes: 3