Symfony - 使用EntityType计算类别

时间:2017-04-27 22:48:22

标签: php forms symfony entity

我有一个从数据库中获取类别的搜索表单,并将每个类别名称显示为一个复选框,它通过EntityType检索,我想在类别名称前面显示计数类别,我设法从数据库中计算每个类别和将结果放在这样的数组中:$ categCount [name] = count;

如何使用EntityType在每个类别名称前显示她的计数?

->add('categories', EntityType::class, ['class' => 'AppBundle:Categorie',
                                                   'choice_label' => 'name',
                                                   'multiple' => true,
                                                   'expanded' => true,
                                                   'required' => false,
        ])

1 个答案:

答案 0 :(得分:1)

现在。我不确定你的实体是怎样的,但如果你在同一个实体中有计数,你可以做类似的事情:

->add('categories', EntityType::class, ['class' => 'AppBundle:Categorie',
                                                   'choice_label' => 'getNameWithCategoriesCount',
                                                   'multiple' => true,
                                                   'expanded' => true,
                                                   'required' => false,
        ])

并在您的实体中

public function getNameWithCategoriesCount(){
    return $this->getName().' '.$this->getCount();
}

或者(未经测试)你可以:

     ->add(
            'categories',
            EntityType::class,
            [
                'class' => 'AppBundle:Categorie',

                'choice_label' => function ($category) use ($this-em) {
                    return $category->getDisplayName() $this->em->getRepo..()->getCount($category);
                },
                'multiple' => true,
                'expanded' => true,
                'required' => false,
            ]
        )

注意:对于此方法,您需要将表单声明为服务并传递entityManager