Create form of Category with SubCategories on Symfony

筅森魡賤 提交于 2021-01-28 12:03:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!