Symfony2 collection of Entities - how to add/remove association with existing entities?

前端 未结 5 567
滥情空心
滥情空心 2020-12-04 06:56

1. Quick overview

1.1 Goal

What I\'m trying to achieve is a create/edit user tool. Editable fields are:

  • username (type: text)
  • plai
5条回答
  •  离开以前
    2020-12-04 07:52

    I've come to the same conclusion that there's something wrong with the Form component and can't see an easy way to fix it. However, I've come up with a slightly less cumbersome workaround solution that is completely generic; it doesn't have any hard-coded knowledge of entities/attributes so will fix any collection it comes across:

    Simpler, generic workaround method

    This doesn't require you to make any changes to your entity.

    use Doctrine\Common\Collections\Collection;
    use Symfony\Component\Form\Form;
    
    # In your controller. Or possibly defined within a service if used in many controllers
    
    /**
     * Ensure that any removed items collections actually get removed
     *
     * @param \Symfony\Component\Form\Form $form
     */
    protected function cleanupCollections(Form $form)
    {
        $children = $form->getChildren();
    
        foreach ($children as $childForm) {
            $data = $childForm->getData();
            if ($data instanceof Collection) {
    
                // Get the child form objects and compare the data of each child against the object's current collection
                $proxies = $childForm->getChildren();
                foreach ($proxies as $proxy) {
                    $entity = $proxy->getData();
                    if (!$data->contains($entity)) {
    
                        // Entity has been removed from the collection
                        // DELETE THE ENTITY HERE
    
                        // e.g. doctrine:
                        // $em = $this->getDoctrine()->getEntityManager();
                        // $em->remove($entity);
    
                    }
                }
            }
        }
    }
    

    Call the new cleanupCollections() method before persisting

    # in your controller action...
    
    if($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        if($form->isValid()) {
    
            // 'Clean' all collections within the form before persisting
            $this->cleanupCollections($form);
    
            $em->persist($user);
            $em->flush();
    
            // further actions. return response...
        }
    }
    

提交回复
热议问题