问题
I have two entities : Category and SubCategory. One category have 0 or many subcategory. They are related with Many-to-One relation. I don't imagine how i can make a form with subcategories group by category like this :
CATEGORY 1 :
- SubCategory 1
- SubCategory 2
CATEGORY 2:
- SubCategory 1
- SubCategory 2
My form actual :
class CategorieType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sous_categories', CollectionType::class, array(
'entry_type' => SousCategorie::class,
'entry_options' => array('label' => false),
))
;
}
Thanks for your help
回答1:
I do that in my form, i obtein the subcategories. How to show them grouped in box by category ?
$builder
->add('sous_categories', EntityType::class, array(
'class' => 'AppBundle:Bdd\SousCategorie',
'query_builder' => function(EntityRepository $er) use ($revue) {
return $er->createQueryBuilder('sc')
->addSelect('sc')
->join('sc.Categorie', 'c')
->andWhere('c.Revue = :Revue')
->setParameter('Revue', $revue)
->orderBy('c.libelle', 'ASC')
->addOrderBy('sc.libelle', 'ASC')
;
},
'choice_label' => function($sousCategorie){
return $sousCategorie->getCategorie()->getLibelle()." - ".$sousCategorie->getLibelle();
},
'multiple' => true,
'expanded' => true,
))
;
回答2:
You can use a groupBy in you repository function :
$builder
->add('sous_categories', EntityType::class, array(
'class' => 'AppBundle:Bdd\SousCategorie',
'query_builder' => function(EntityRepository $er) use ($revue) {
return $er->createQueryBuilder('sc')
->addSelect('sc')
->join('sc.Categorie', 'c')
->andWhere('c.Revue = :Revue')
->setParameter('Revue', $revue)
->orderBy('c.libelle', 'ASC')
->addOrderBy('sc.libelle', 'ASC')
->groupBy('sc.Categorie')
;
},
'choice_label' => function($sousCategorie){
return $sousCategorie->getCategorie()->getLibelle()." - ".$sousCategorie->getLibelle();
},
'multiple' => true,
'expanded' => true,
))
;
来源:https://stackoverflow.com/questions/49197407/create-form-of-category-with-subcategories-on-symfony