2013-10-07 62 views
0

我必須更改使用不同類型生成表單的網頁。有一個在包/表/文件夾2個文件:使用表格的良好做法

  • ProductType.php
  • ProductEditType.php

它的正常工作,第一個是用來產生新的產品形態和第二一個是編輯它的表單。

這兩個文件幾乎95%是相同的,所以我想它必須以任何方式使用一種類型來生成多個表單。

我一直在閱讀如何使用表單事件來修改表單,但我還沒有找到清楚的是關於它的一般良好實踐。

非常感謝。

更新

我寫了一個事件訂閱如下。

<?php 
namespace Project\MyBundle\Form\EventListener; 

use Symfony\Component\Form\FormEvent; 
use Symfony\Component\Form\FormEvents; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 

/** 
* Description of ProductTypeOptionsSubscriber 
* 
* @author Javi 
*/ 
class ProductTypeOptionsSubscriber implements EventSubscriberInterface 
{ 
    public static function getSubscribedEvents() { 
     return array(FormEvents::PRE_SET_DATA => 'preSetData'); 
} 

public function preSetData(FormEvent $event){ 

    $data = $event->getData(); 
    $form = $event->getForm(); 

    if(!$data || !$data->getId()){ 
     // No ID, it's a new product 
     //.... some code for other options ..... 
     $form->add('submit','submit', 
      array(
       'label' => 'New Produtc', 
       'attr' => array('class' => 'btn btn-primary') 
       )); 
    }else{ 
     // ID exists, generating edit options ..... 
     $form->add('submit','submit', 
      array(
       'label' => 'Update Product', 
       'attr' => array('class' => 'btn btn-primary') 
       )); 
    } 

} 
} 

在ProductType,裏面buildForm:

$builder->addEventSubscriber(new ProductTypeOptionsSubscriber()); 

所以這一切,這是很容易寫,並能正常工作。

回答

0

你可以閱讀這本食譜event subscriber,第一種情況可以爲你做。

返回到文檔的例子..

,你希望他們添加字段,以這種方式被修改:

$builder->addEventSubscriber(new AddNameFieldSubscriber()); 

然後輸入你的邏輯創建事件事件訂閱:

// src/Acme/DemoBundle/Form/EventListener/AddNameFieldSubscriber.php 
namespace Acme\DemoBundle\Form\EventListener; 

use Symfony\Component\Form\FormEvent; 
use Symfony\Component\Form\FormEvents; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 

class AddNameFieldSubscriber 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(); 

     // check if the product object is "new" 
     // If you didn't pass any data to the form, the data is "null". 
     // This should be considered a new "Product" 
     if (!$data || !$data->getId()) { 
      $form->add('name', 'text'); 
      .... 
      ..... // other fields 
     } 
    } 
} 
+0

謝謝,我來看看。 – Javi