在Symfony上创建包含SubCategories的类别表单

时间:2018-03-09 15:49:33

标签: database symfony orm doctrine

我有两个实体:Category和SubCategory。一个类别有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),
            ))
        ;
    }

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

我以我的形式这样做,我注意子类别。如何按类别显示它们分组?

$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,
        ))
    ;

答案 1 :(得分:0)

您可以在存储库功能中使用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,
        ))
    ;