我有两个实体:类别和子类别。一个类别有0个或多个子类别。它们是多对一的关系。 我不想象如何制作一个包含子类别的表单,如下所示:
CATEGORY 1 :
- SubCategory 1
- SubCategory 2
CATEGORY 2:
- SubCategory 1
- SubCategory 2
我的实际表格:
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),
))
;
}
感谢您的帮助
我以我的形式做到这一点,我获得了子类别。如何将它们按类别分组显示在框中?
$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,
))
;
您可以在存储库函数中使用 groupBy :
$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,
))
;
->add('sous_categories', EntityType::class, [
'class' => SousCategorie::class,
'group_by' => function($souscategory) {
return $souscategory->getCategory()->getName();
},
'choice_label' => function ($souscategory) {
return $souscategory->getName();
},
])