doudouwen2763
2015-04-14 18:43
浏览 62
已采纳

如何在Symfony2表单上动态选择EntityManager以与ManyToMany一起使用

I have a Symfony2 bundle where I am utilizing a dynamic selection of EntityManagers based on the subdomain in addition to a fixed EM for general settings, etc. For example, a user lands on dev.mydomain.com and is presented with a login screen that pulls information from a default database containing site title, colors, etc. The login script, however, references the dev database which contains the users and data for that subdomain. Similarly, when logging into other.mydomain.com, the login references the other database. This all works great and users are validated against their appropriate databases.

The issue I'm encountering is when I create a "new user form" using Symfony's Form system. I utilize a Many to Many relationship for user roles as outlined by The Book, but can't find a way to specify which EntityManager is used, causing it to look for the relationships against the default EntityManager.

Controller/UserController.php

public function addAction(Request $request) {

    $us = new User();

    // ORM Connection name stored in session from the login screen
    $em = $this->getDoctrine()->getManager(
        $request->getSession()->get('database')
    );

    $form = $this->createForm(
        new UserType($em), $us
    );

    return $this->render(
        'MyBundle:User:create.html.twig',
        array( 'form' => $form->createView() )
    );
}

Entity/User.php

/**
 * @var string
 *
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist"})
 */
private $roles;

config.yml

doctrine:
  dbal:
    connections:
        default:
            driver:   "%database_driver%"
            host:     "%database_host%"
            port:     "%database_port%"
            dbname:   "%database_name%"
            user:     "%database_user%"
            password: "%database_password%"
            charset:  UTF8
        dev:
            driver:   "%dev.database_driver%"
            host:     "%dev.database_host%"
            port:     "%dev.database_port%"
            dbname:   "%dev.database_name%"
            user:     "%dev.database_user%"
            password: "%dev.database_password%"
            charset:  UTF8
orm:
  default_entity_manager: default
  auto_generate_proxy_classes: "%kernel.debug%"
  entity_managers:
    default:
        connection: default
        mappings:
            MyBundle: ~
    dev:
        connection: dev
        mappings:
            MyBundle: ~

Is there a way to pass a specified EntityManager into createForm or FormBuilder to be utilized by the built-in ManyToMany ORM annotation? To be clear, the rest of the form works appropriately, adding the user to the desired EntityManager -- it's just the Roles field that's still referencing default.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题