Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a form as a service in Symfony2

Tags:

php

symfony

What I'd like to be able to do from any controller is:

$register = $this->get('register_manager');
return $this->render(
    'AcmeUserBundle:Account:register.html.twig',
     array(
         'form' => $register->getRegistrationForm(),
         )
 );

And in my template

<form>
    {{ form_widget(form) }}
</form>

Here's how I have set up so far

In my Acme/UserBundle/Resources/config/services.yml I have

parameters:
    register_manager.class: Acme\UserBundle\Manager\RegisterManager

services:
    register_manager:
        class:     %register_manager.class%
        arguments: [@form.factory]

In RegisterManager.php I have

namespace Acme\UserBundle\Manager;

use Acme\UserBundle\Form\Type\RegistrationType;
use Symfony\Component\Form\FormFactoryInterface;

class RegisterManager
{

    protected $formFactory;

    public function __construct(FormFactoryInterface $formFactory)
    {
        $this->formFactory = $formFactory;
    }


    public function getRegistrationForm()
    {
        return $this->formFactory->createBuilder(new RegistrationType());
    }
}

And in Acme\UserBundle\Form\Type\RegistrationType I have:

namespace Acme\UserBundle\Form\Type;

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

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('username','text');
        $builder->add('email','email');
        $builder->add('password','password');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Acme\UserBundle\Entity\User',
        );
    }

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

I know the RegistrationType() works as I've had it in a controller. My problem is with setting up RegisterManager as a service, I can't get the right components in there and I'm not sure where to look.

like image 739
ed209 Avatar asked Nov 12 '11 20:11

ed209


1 Answers

You're almost there, it seems. To get a Form object from your service, you should use FormFactoryInterface::create() instead of FormFactoryInterface::createBuilder()

The reason why $this->createForm() works in controllers is because every controller is extending the base controller, which happens to implement this method.

I have found my IDE's ability to link to specific Symfony files highly helpful and I suggest you use one, if you already aren't. There's also a git repository, which you can find here.

like image 181
kgilden Avatar answered Oct 18 '22 10:10

kgilden