Nicolas Ardison
Nicolas Ardison

Reputation: 93

Extending form types in Symfony2 (aka creating a new form widget)

I'm trying to create/expand a form type in Symfony2, what i want to make is a category selector like in the following image. For that i was reading in symfony2 doc, The chapter: "How to create custom field type"(http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html)

Category widget The table database for this this have the following aspect...

enter image description here What i pretend it's in Symfony extend the hidden form type widget to create my own type, I can not find in the documentation of symfony how to access to the Entities data from the custom type, and also how to call to the custo type object methods in the twig file of the widget. (In the example the twig file is src/Acme/DemoBundle/Resources/views/Form/fields.html.twig )


I know that i have to do some ajax callings to auto load the subcategories every time somebody touch a category, i have done this in the controller, but firstly i want to know how to do what i wrote. Wish this widget be reusable for all :).

Thanks a lot guys!

Upvotes: 3

Views: 5115

Answers (1)

Mehdi Chamouma
Mehdi Chamouma

Reputation: 97

You should declare your new type as service and inject the Entity Manager into it :

namespace Your\Bundle\Form\Type;

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

use Doctrine\ORM\EntityManager;

class NewExampleType extends AbstractType
{

    protected $em;

    public function __construct(EntityManager $entityManager)
    {
        $this->em = $entityManager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        //your code
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        //your code
    }

    public function getParent()
    {
        return 'hidden';
    }

    public function getName()
    {
        return 'example_widget';
    }
}

Then, declare new service in services.yml

services:
  example.type:
    class:  Your\Bundle\Form\Type\NewExampleType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type, alias: "example_widget" }

Source: http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html#creating-your-field-type-as-a-service

Then, you should take a look here : http://symfony.com/doc/current/cookbook/form/data_transformers.html

Upvotes: 3

Related Questions