Geo*_* V. 3 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 "
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
更通用的解决方案是创建一个新的表单类型扩展并为所有类型注册它.
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'];
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务配置:
services:
acme_demo_bundle.special_width_type_extension:
class: Acme\DemoBundle\Form\Extension\SpecialWidthTypeExtension
tags:
- { name: form.type_extension, alias: field }
Run Code Online (Sandbox Code Playgroud)
在Twig中,您必须检查是否设置了新选项:
{% if width is not null %}
<div class='col-sm-{{ width }}'>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1757 次 |
最近记录: |