编程语言
首页 > 编程语言> > php – Symfony2 – 创建字段集

php – Symfony2 – 创建字段集

作者:互联网

我正在尝试创建一个基本的fieldset模板.我有的是这个:

fieldset.html.twig

{% form_theme form _self %}
{% block form_row %}
    <fieldset>
        <legend></legend>
        {{ form_row(form) }}
    </fieldset>
{% endblock %}

FieldsetType.php

class FieldsetType extends AbstractType
{
    public function __construct($tituloFieldset="")
    {
        $this->titulo = $tituloFieldset;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'attr' => array(
                'title'=>$this->titulo
            ),
           'mapped'=>false
        ));
    }

    public function getParent()
    {
        return 'form';
    }

    public function getName()
    {
        return 'fieldset';
    }

    private $titulo;
}

目前的用法

$builder->add('nestedform', new FieldsetType('legend'));

我已经尝试了所有方法:将标题添加为标签(没有字段渲染的额外标签),模板化整个表单(在这种情况下我不能添加额外的字段集),等等.

我该怎么办?

解决方法:

我已将此功能提取到一个包中,因为我需要在一些项目https://github.com/adamquaile/AdamQuaileFieldsetBundle

但基于其他一些答案和想法,它相当于:

class FieldsetType extends AbstractType {

    public function setDefaultOptions ( OptionsResolverInterface $resolver )
    {
        $resolver->setDefaults([
            'legend'    => '',
            'virtual'   => true,
            'options'   => array(),
            'fields'    => array(),
        ]);
    }

    public function buildForm ( FormBuilderInterface $builder, array $options )
    {
        if ( !empty($options['fields']) ) {

            foreach ( $options['fields'] as $field ) {
                $builder->add($field['name'], $field['type'], $field['attr']);
            }
        }
    }

    public function buildView ( FormView $view, FormInterface $form, array $options )
    {
        if (false !== $options['legend']) {
            $view->vars['legend'] = $options['legend'];
        }
    }

    public function getName()
    {
        return 'fieldset';
    }
}

标签:php,forms,symfony,fieldset
来源: https://codeday.me/bug/20190718/1492394.html