简体   繁体   中英

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?

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,

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())
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM