smarber
smarber

Reputation: 5084

symfony2: dependency injection for forms

Actually I'm rather confused about the best way to pass arguments to a form. As far as I know, there are three ways:

  1. To turn the form class into a service

  2. To pass arguments through the array options

  3. To pass argument through the constructor of the form class

What would be the best/cleanest way?

Upvotes: 0

Views: 124

Answers (2)

jamek
jamek

Reputation: 812

In my opinion:

  1. To turn the form class into a service - you use if arguments are available by DI, like EntityManager, Router and other services etc.
  2. To pass arguments through the array options - "static" data like: show this field for admin only,

Upvotes: 1

George
George

Reputation: 1499

For the majority of my forms, I create a separate form class. When I need to render the form with prepopulated data, I load the entity in my controller and pass that entity when construction the form. For example, if I have an entity called $user linked to registration entity, I will populate my form like this:

    $registration = $user->getRegistration();

    $form = $this->createForm(new RegistrationType(), $registration, array());

Then I render the $form in twig:

    return $this->render(
       'AcmeAccountBundle:Account:register.html.twig',
        array('form' => $form->createView())
    );

Upvotes: 0

Related Questions