如何覆盖所有symfony2表单类型并添加一些属性(在2.2版中)?

时间:2014-06-19 13:31:08

标签: symfony symfony-2.2

我希望所有表单类型都具有width属性,并且像这样使用它:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('product_name', 'text', array('width' => "small"));
}

public function buildView(FormView $view, FormInterface $form, array $options)
{
    parent::buildView($view, $form, $options);
    if (array_key_exists(self::OPTION_WIDTH, $options)) {
        $view->vars["attr"]["class"] .= " class_1 class_2 "
    }
}

2 个答案:

答案 0 :(得分:5)

更通用的解决方案是创建一个新的表单类型扩展并为所有类型注册它。

Symfony文档非常清楚地描述了如何创建新的表单类型扩展: http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html

但它没有提及如何所有类型注册该扩展名。

“技巧”是指定“字段”(或“表格”来自Symfony 2.3和下一个)作为扩展类型(因此在getExtendedType()中作为服务中的别名)配置)

// src/Acme/DemoBundle/Form/Extension/SpecialWidthTypeExtension.php
namespace Acme\DemoBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SpecialWidthTypeExtension extends AbstractTypeExtension
{
    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return 'field'; // extend all types
    }

    /**
     * Add the width option
     *
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setOptional(array('width'));
    }

    /**
     * Pass the extra parameters to the view
     *
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (array_key_exists('width', $options)) {
            // set an "width" variable that will be available when rendering this field
            $view->vars['width'] = $options['width'];
        }
    }
}

服务配置:

services:
    acme_demo_bundle.special_width_type_extension:
        class: Acme\DemoBundle\Form\Extension\SpecialWidthTypeExtension
        tags:
            - { name: form.type_extension, alias: field }

在Twig中,您必须检查是否设置了新选项:

{% if width is not null %}
    <div class='col-sm-{{ width }}'>
{% endif %}

答案 1 :(得分:0)

将其添加为属性...

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('product_name', 'text', array(
        'attr' => array(
            'width' => "small",
        )
    );
}

然后它将在您的字段中显示为width="small"