Skip to content

Instantly share code, notes, and snippets.

@asentner
Last active September 13, 2015 01:50
Show Gist options
  • Save asentner/c6f0e8ff8d4a38052137 to your computer and use it in GitHub Desktop.
Save asentner/c6f0e8ff8d4a38052137 to your computer and use it in GitHub Desktop.
Symfony FieldsetType using anonymous functions instead of arrays
<?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';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment