Symfony2 Form Builder Select Across Join Table with Metadata

后端 未结 3 2050
广开言路
广开言路 2021-02-03 12:40

I have 3 entities:

[Member] ----OneToMany----> [MemberCategory] ---ManyToOne---> [Category]

This works well as far as fetching results fr

3条回答
  •  难免孤独
    2021-02-03 13:16

    The post of cheesemacfly is not so bad, but it is call embeded form and can be complicated to manage. In fact, you jus need to create a "Custom Repositories" http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

    It will add a new methods for "grabbing" your ORM object with Doctrine2 like find() or findBy();

    1) Create a new repository in a Repository Folder of your Bundle

    createQueryBuilder('c')
             ->leftJoin('c.Member', 'mc')
             ->where('mc.member = ?1')
             ->setParameter(1, $member);
    }
    

    }

    2) Attached your Cutom repository to your Entity

    namespace YourVendor\SMWMemberBundle\Entity;
    use Doctrine\ORM\Mapping as ORM;
    
    /**
    * @ORM\Entity(repositoryClass="YourVendor\SMWMemberBundle\Entity\ProductRepository")
    * @ORM\Table(name="Category") 
    */
    class Category{
    

    3) add a constructor to your Form class and pass de Entity Manager and the variable required to your query :

    class CategoryUserForm extends AbstractType
    {
       private $em;
       private $member ;
    
    
       public function __construct(EntityManager $em, $site, $seed)
       {
           $this->em = $em;
           $this->member = $member;
    
       }
    
    public function buildForm(FormBuilder $builder, array $options)
    {
        $qb = $this->em->getRepository('SMWMemberBundle:Category')->UsedByUsers($this->member);
        $builder->add('categories', 'entity', array(
            'class' => 'SMWMemberBundle:MemberCategory',
            'query_builder'     => $qb,
            'multiple'     => true,
            'expanded'     => true,
            'required' => false
        ));
     }
    

    4) In your controller, you create your form like that :

    $editForm = $this->createForm(new CategoryUserForm($em, $member), $category);
    

    Feel free to ask me questions, I'm hope this is what you are looking for ;)

提交回复
热议问题