Question

I'm trying to create a basic fieldset template. What I have is this:

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;
}

Current usage

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

I've tried everything: adding the title as a label (an extra label with no field renders), templating the whole form (in which case I cannot add extra fieldsets), etcetera.

What should I do?

Was it helpful?

Solution

I've extracted this functionality into a bundle, as I needed it in a few projects https://github.com/adamquaile/AdamQuaileFieldsetBundle

But based on a few other answers and ideas around, it amounts to this:

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';
    }
}

OTHER TIPS

You are on the right track. You can find a simple example here: https://gist.github.com/spcmky/8512371

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top