Adding a new form field type in symfony2

I am currently looking into Symfony2 to see what it can do for me, and one of the things that I wanted to do was to use their new shiny form api to do the old create form, validate on client, validate on server and store the changes loop that everybody does. As is always the case, such solutions meets all the immediate needs and customizing the one-off cases is not a big hassle. Other times you see something that you would want to streamline for future reuse and that is the use-case that this post is all about.

This post has been published a bit prematurely and may not be accurate, but atleast it is out there.

There should be cookbook about this at http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html. But it is still missing while I write this, fortunately I got a few pointers on the #symfony irc channel and the excellent working example of: http://symfony2bundles.org/simplethings/SimpleThingsFormExtraBundle

So in brief what you need to do:
1. Implement a form field by extending AbstractType
2. Create a twig block widget for display
3. Tell form component about the new field
4. Make the block widget be loaded

Implement a form field by extending AbstractType, I recommend you look at the API of AbstractType (http://api.symfony.com/2.0/Symfony/Component/Form/AbstractType.html).

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class MyFieldType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options)
{
}
public function buildView(FormView $view, FormInterface $form)
{
}

/**
* Default options
*
* @param array $options
* @return array
*/
public function getDefaultOptions(array $options)
{
//var_dump($options); die();
return array( 'max' => false );
}

/**
* @param array $options
* @return string
*/
public function getParent(array $options)
{
return 'field';
}

/**
* Used to identify the rendering block
* Note that _widget is added to the last bit.
*/
public function getName()
{
return 'my_myfield';
}

}

To add the type to something.
type by describing the service

by the twig form by adding a compiler pass.

Leave a Reply