February 9, 2014
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
}
//----
}
I'm a 32-years old programmer and web developer currently living in Montevideo, Uruguay. I been programming since I was about 15 y.o, and for the past 12 actively working in the area.