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