Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate a form as a service in Symfony2
    text
    copied!<p>What I'd like to be able to do from any controller is:</p> <pre><code>$register = $this-&gt;get('register_manager'); return $this-&gt;render( 'AcmeUserBundle:Account:register.html.twig', array( 'form' =&gt; $register-&gt;getRegistrationForm(), ) ); </code></pre> <p>And in my template</p> <pre><code>&lt;form&gt; {{ form_widget(form) }} &lt;/form&gt; </code></pre> <p><strong>Here's how I have set up so far</strong></p> <p>In my <code>Acme/UserBundle/Resources/config/services.yml</code> I have</p> <pre><code>parameters: register_manager.class: Acme\UserBundle\Manager\RegisterManager services: register_manager: class: %register_manager.class% arguments: [@form.factory] </code></pre> <p>In <code>RegisterManager.php</code> I have</p> <pre><code>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-&gt;formFactory = $formFactory; } public function getRegistrationForm() { return $this-&gt;formFactory-&gt;createBuilder(new RegistrationType()); } } </code></pre> <p>And in <code>Acme\UserBundle\Form\Type\RegistrationType</code> I have:</p> <pre><code>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-&gt;add('username','text'); $builder-&gt;add('email','email'); $builder-&gt;add('password','password'); } public function getDefaultOptions(array $options) { return array( 'data_class' =&gt; 'Acme\UserBundle\Entity\User', ); } public function getName() { return 'registration'; } } </code></pre> <p>I know the <code>RegistrationType()</code> works as I've had it in a controller. My problem is with setting up <code>RegisterManager</code> as a service, I can't get the right components in there and I'm not sure where to look.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload