Sunday, February 9, 2014

Using the Symfony OptionsResolver interface with Custom Forms

My beloved Symfony changed a lot since last time we seen. Now when trying to update some projects to 2.4 many things broke including my hearth. But after the initial annoyance of any migration i realize some things were better, even new. This is the case of the new OptionsResolver component.
This is used by several components, but the one i liked was when we apply it to custom Form classes.
See, back in time if we wanted to pass some parameters to our Form class we had to use the native PHP constructors, do some fancy stuff.... include some checks and your initial simple class became a big mess.

So this is a new approach you could try:

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GalleryEditor extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    // Access your options here using something like: $options['db']
  }

  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    // I think function names are self-explanatory here
    $resolver
      ->setRequired(array(
         'db'
      ))
      ->setAllowedTypes(array(
         'db' => 'Doctrine\DBAL\Connection'
    ));
    // Other ones you could use are:
    // - setOptional
    // - setDefaults
  }

  //----
}

For much I hate code-snippet posts i really liked this one.... also to not let my blog die for another 6 months (again)