Symfony 2 Forms 实体字段类型分组 [英] Symfony 2 Forms entity Field Type grouping
问题描述
我正在 Symfony2 中渲染一个表单,其中 data_class 映射到 Reservation
实体,并且这个表单有一个实体字段类型,属于 Service
类.Reservation
和 Service
类之间的关系是多对多的.然后一个服务有一个 ServiceType
,它是另一个类,从 Service
类
I'm rendering a form in Symfony2 with data_class mapped to Reservation
entity, and this form has a entity field type, of class Service
. The relation between Reservation
and Service
class is many to many. A service then has a ServiceType
, which is another class, that is mapped as many to one from the Service
class
我想要做的是在预订表单中将所有服务显示为复选框,按服务类型分组.到目前为止,我可以像这样一起显示所有服务(代码来自 ReservationType
类):
What I want to do is display all services as checkboxes in the reservation form, grouped by service type. So far, I can display all the services together like this (the code is from ReservationType
class):
$builder->add('services','entity', array(
'class' => 'MyBundle:Service',
'multiple' => true,
'expanded' => true
));
并以默认方式显示表单:
And displaying the form the default way:
<form action="{{ path('reservations', {'step': 2}) }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
结果是这样的:
□ servicetype1 option
□ servicetype1 another option
□ servicetype2 option
□ servicetype2 another option
我想实现的是:
servicetype1:
□ option
□ another option
servicetype2:
□ option
□ another option
我试图通过使用这样的 query_builder 选项来仅指定服务的子集:
I was trying to specify only subsets of services by using query_builder option like this:
$builder->add('services','entity', array(
'class' => 'MyBundle:Service',
'multiple' => true,
'expanded' => true,
'query_builder' => function (MyBundleEntityServiceRepository $repository)
{return $repository->createQueryBuilder('s')->where('s.serviceType = ?1')->setParameter(1, 1);} ));
$builder->add('services','entity', array(
'class' => 'MyBundle:Service',
'multiple' => true,
'expanded' => true,
'query_builder' => function (MyBundleEntityServiceRepository $repository)
{return $repository->createQueryBuilder('s')->where('s.serviceType = ?1')->setParameter(1, 2);} ));
这是错误的,因为:
- 我必须指定
ServiceType
id - 将
'services'
添加到构建器两次,将覆盖第一次添加(这是合乎逻辑的,但无法在不更改实体的情况下解决)
- I have to specify the
ServiceType
id - Adding the
'services'
to the builder twice, will overwrite the first addition (which is logical, but cannot be solved without changing the entities)
处理此类表单的最佳选择是什么?到目前为止只有 2 个 ServiceType
-s,但我想让它保持动态和可重用.
What would be the best option for handling forms like this? There are only 2 ServiceType
-s so far, but I would like to keep it dynamic, and reusable.
推荐答案
这可以通过使用 group_by 选项:
$builder->add('services','entity', array(
'class' => 'MyBundle:Service',
'group_by' => 'serviceType',
'multiple' => true,
'expanded' => true
));
这篇关于Symfony 2 Forms 实体字段类型分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!