使用表格的良好做法

时间:2013-10-07 18:29:19

标签: symfony

我必须更改使用不同类型的网站来生成表单。在Bundle / Form /文件夹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());

所以就是这样,它很容易编写,而且工作正常。

1 个答案:

答案 0 :(得分: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
        }
    }
}