这源于这个问题,但我的问题略有改变:Odd many-to-many form rendering with symfony and dictionary
我的实体是 Formula 一对多与 FormulaColor 多对一与 Color。
公式(id、代码、名称) FormulaColor(formula_id、color_id、百分比) 颜色(id、代码、名称)
一个公式可以有一种或多种颜色,每种颜色占该公式的百分比。
我正在尝试创建一个公式编辑类型,它将显示给定公式的百分比字段以及每个百分比字段的标签或标题,即标签的颜色->名称。我已经显示了公式的百分比字段,但我想用颜色名称标记每个字段。我怎样才能做到这一点?我必须以某种方式使用查询构建器吗?
我有一个看起来像这样的 FormulaAddEditType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('code', null, array(
'label' => 'Code'
))
->add('name', null, array(
'label' => 'Name'
));
$builder->add('formulaColors', 'collection', array(
'type' => new FormulaColorType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
));
}
然后是 FormulaColorType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('percentage', 'number', array(
'label' => new ColorAddEditType()
));
}
颜色添加编辑类型
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('code', null, array(
'label' => 'Code'
))
->add('name', null, array(
'label' => 'Name'
))
;
}
控制器动作
/**
* @Route("/formulas/{id}/edit")
* @Method({"GET", "POST"})
* @Template()
*/
public function editAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$formula = $em->getRepository('PrismPortalCommonBundle:Formula')->find($id);
if (!$formula) {
throw $this->createNotFoundException('Unable to find Formula entity.');
}
$form = $this->createForm(new FormulaAddEditType(), $formula);
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$em->persist($formula);
$em->flush();
return $this->redirect($this->generateUrl('prism_portal_admin_dashboard_index'));
}
}
return array(
'formula' => $formula,
'form' => $form->createView()
);
}
我能够在表单事件订阅者中获得我想要的结果。订阅者如下所示:
class AddPercentFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// Tells the dispatcher that you want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
// If it's not a new Formula, then I want to show the percentage fields.
if ($data) {
$form->add('percentage', 'text', array(
'label' => $data->getColor()->getCode(),
));
}
}
}