gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:25:38 24 4
gpt4 key购买 nike

我希望所有表单类型都具有 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 "
}
}

最佳答案

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

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

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

“技巧”是指定“field”(或 Symfony 2.3 及下一个版本中的“form”) 作为扩展类型(作为 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 %}

关于symfony - 如何覆盖所有 symfony2 表单类型并添加一些属性(在版本 2.2 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24307849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com