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());
所以這一切,這是很容易寫,並能正常工作。
謝謝,我來看看。 – Javi