Inspired by: https://github.com/adamquaile/AdamQuaileFieldsetBundle.
This example is using an anonymous function instead of an array to pass the sub types to the FieldsetType from your FormBuilder.
Inspired by: https://github.com/adamquaile/AdamQuaileFieldsetBundle.
This example is using an anonymous function instead of an array to pass the sub types to the FieldsetType from your FormBuilder.
<?php | |
namespace Acme\DemoBundle\Form\Type; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
use Symfony\Component\Validator\Constraints as Assert; | |
class ExampleFormType extends AbstractType | |
{ | |
/** | |
* @param FormBuilderInterface $builder | |
* @param array $options | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder->add('testFieldset', 'fieldset', [ | |
'legend' => 'Test Fieldset!', | |
'types' => function(FormBuilderInterface $builder) { | |
$builder->add('testField', 'text', [ | |
'label' => 'A test field in the fieldset' | |
'attr' => [ | |
'class' => 'another-test-class', | |
], | |
]); | |
} | |
]); | |
} | |
/** | |
* @param OptionsResolver $resolver | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults([ | |
'attr' => [ | |
'novalidate' => 'novalidate', | |
'id' => 'form-example-form', | |
], | |
]); | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() | |
{ | |
return 'example'; | |
} | |
} |
<?php | |
namespace Acme\DemoBundle\Form\Type; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\Form\FormView; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
class FieldsetType extends AbstractType | |
{ | |
/** | |
* @param FormBuilderInterface $builder | |
* @param array $options | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
// execute the callable with our FormBuilder passed as an argument | |
$options['types']($builder); | |
} | |
/** | |
* @param FormView $view | |
* @param FormInterface $form | |
* @param array $options | |
*/ | |
public function buildView(FormView $view, FormInterface $form, array $options) | |
{ | |
if (false !== $options['legend']) { | |
$view->vars['legend'] = $options['legend']; | |
} | |
} | |
/** | |
* @param OptionsResolver $resolver | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults([ | |
'legend' => false, | |
'virtual' => true, | |
'types' => null, | |
]) | |
->setAllowedTypes([ | |
'types' => 'callable', | |
]) | |
->setRequired([ | |
'types', | |
]); | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() | |
{ | |
return 'fieldset'; | |
} | |
} |