這源於這個問題,但我的問題稍微修改表單標籤:Odd many-to-many form rendering with symfony and doctrine顯示AA相關實體屬性值在symfony中
我的實體是一級方程式一對多與FormulaColor多到一個彩色。
式(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()
));
}
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(),
));
}
}
}
請將控制器代碼發佈到創建此表單的位置。 – Lighthart 2013-05-02 14:42:06
@Lighthart我已經添加了控制器的動作。 – 2013-05-02 17:18:48
這些標籤僅適用於現有公式? – Lighthart 2013-05-02 17:37:21