这源于这个问题,但我的问题略有改变:Odd many-to-many form rendering with symfony and doctrine
我的实体是 Formula 与 FormulaColor 的一对多与 Color 的多对一。
公式(id、代码、名称) FormulaColor(公式_id、颜色_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()
));
}
ColorAddEditType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('code', null, array(
'label' => 'Code'
))
->add('name', null, array(
'label' => 'Name'
))
;
}
Controller 操作
/**
* @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(),
));
}
}
}
最佳答案
我对您的实体的外观进行了一些猜测,但我认为这大致就是您想要的,例如:
公式添加编辑类型
public function buildForm(FormBuilderInterface $builder, array $options) {
$entity=$builder->getData();
$colors=$entity->getColors());
$builder
->add('code', null, array(
'label' => 'Code'
))
->add('name', null, array(
'label' => 'Name'
));
$colors->map(function ($color) use ($builder) {
$builder->add($color->getName()
, null,
array(
'label' => $color->getName()
)
)
});
}
关于symfony - 在 symfony 中将相关实体属性值显示为表单标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16336644/