【问题标题】:Array Collection, symfony: add a relation [closed]数组集合,symfony:添加关系 [关闭]
【发布时间】:2014-01-29 11:38:59
【问题描述】:

我是 Symfony 和 php 的新手,我试图在没有结果的情况下理解数组集合。

现在我有两个实体,Mission 和 User,与 ManytoMany 相关。我有一个创建新任务的表单和一个创建新用户的表单。

现在我必须创建一个“modifyMissionAction”,允许我为该任务设置用户,但我不明白如何去做。 我阅读了文档here,但没有帮助。我该怎么办?

谢谢

这是我的用户实体是:

 abstract class User extends BaseUser
 {

      /**
      * @var \Doctrine\Common\Collections\ArrayCollection
      * 
      * @ORM\ManyToMany(targetEntity="Acme\ManagementBundle\Entity\Mission", inversedBy="users", orphanRemoval=true)
      * @ORM\JoinTable(name="user_mission")
      */
     private $missions;    
     /**
      * Add missions
      *
      * @param \Acme\ManagementBundle\Entity\Mission $missions
      * @return User
      */
     public function addMission(\Acme\ManagementBundle\Entity\Mission $missions)
     {
         $this->missions[] = $missions;

         return $this;
     }
//...

还有我的任务实体:

<?php

namespace Acme\ManagementBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * @ORM\Entity
 */
class Mission {
    /** 
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var integer
     */
    protected $id;
        /** 
     * @ORM\Column(type="string", length=60)
     * @var String
     */
    protected $name;
    /** 
     * @ORM\Column(type="string", length=600)
     * @var String
     */
    protected $description;
    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Acme\ManagementBundle\Entity\User", mappedBy="missions", cascade={"all"}, orphanRemoval=true)
     */
    private $users;

    public function __construct(){
        $this -> users = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Mission
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Mission
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Add users
     *
     * @param \Acme\ManagementBundle\Entity\User $users
     * @return Mission
     */
    public function addUser(\Acme\ManagementBundle\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \Acme\ManagementBundle\Entity\User $users
     */
    public function removeUser(\Acme\ManagementBundle\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getUsers()
    {
        return $this->users;
    }
    public function __toString()
    {
        return $this->name;
    }
}

【问题讨论】:

    标签: php symfony many-to-many arraycollection


    【解决方案1】:

    首先不要忘记为类和初始化 ArrayCollection 添加 __constructor:

    //src/WebHQ/NewBundle/Entity/Mission.php
    //...
    public function __construct()
    {
        $this->users = new ArrayCollection();
    }
    //...
    

    我假设您想添加控制器动作,女巫允许您将用户对象或对象与任务对象相关联。请阅读 Symfony book 的嵌入表单部分

    然后创建您的操作。最重要的是添加表单元素,其中嵌入了用户实体的表单:

    // src/WebHQ/NewBundle/Controller/MissionController.php
    //...
    public function newAction(Request $request)
    {
        $object = new \WebHQ\NewBundle\Entity\Mission();
    
        $form = $this->createFormBuilder($object)
                ->add('name', 'text')
                //...
                // Users objects embed form
                ->add('users', 'user')
                //...
                ->add('save', 'submit')
                ->getForm();
    
        if ($request->isMethod('POST')) {
            $form->bind($request);
    
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($object);
                $em->flush();
    
                return $this->redirect($this->generateUrl('web_hq_new_mission_index'));
            }
        }
    
        return $this->render('WebHQNewBundle:Mission:new.html.twig', array(
            'form'      => $form->createView(),
            //...
        ));
    }
    
    public function editAction($id, Request $request)
    {
        $object = $this->getDoctrine()
                ->getRepository('WebHQNewBundle:Mission')
                ->find($id);
    
        $form = $this->createFormBuilder($object)
                ->add('name', 'text')
                //...
                ->add('users', 'user')
                //...
                ->add('save', 'submit')
                ->add('delete', 'submit')
                ->getForm();
    
        if ($request->isMethod('POST')) {
            $form->bind($request);
    
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $form->get('save')->isClicked() ? $em->persist($object) : $em->remove($object);
                $em->flush();
    
                return $this->redirect($this->generateUrl('web_hq_new_mission_index'));
            }
        }
    
        return $this->render('WebHQNewBundle:Mission:edit.html.twig', array(
            'form'      => $form->createView(),
            //...
        ));
    }
    //...
    

    检查您的路线。您应该有使用{id} 参数进行编辑操作的路线。如果参数名称不适合您在路由和函数定义中更改它:

    // src/WebHQ/NewBundle/Resources/config/route.yml
    //...
    web_hq_new_mission_new:
        pattern: /mission/new
        defaults: { _controller: WebHQNewBundle:Mission:new }
    
    web_hq_new_mission_edit:
        pattern: /mission/{id}/edit
        defaults: { _controller: WebHQNewBundle:Mission:edit }
    //...
    

    然后为用户对象定义表单类型:

    // src/WebHQ/NewBundle/Form/Type/UserType.php
    namespace WebHQ\NewBundle\Form\Type;
    
    use Doctrine\ORM\EntityRepository;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\OptionsResolver\Options;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    
    
    class UserType extends AbstractType
    {
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'class' => 'WebHQNewBundle:User',
                'property' => 'name',
                'empty_value' => 'Choose',
                'required' => true,
                'multiple' => true,
                'query_builder' => function (Options $options) {
                    return function(EntityRepository $er) use ($options) {
                        return $er->createQueryBuilder('c')
                            ->orderBy('c.name', 'ASC');
                    };
                },
            ));
        }
    
        public function getParent()
        {
            return 'entity';
        }
    
        public function getName()
        {
            return 'user';
        }
    }
    

    并在 service.yml 中注册一个类型:

    # src/WebHQ/NewBundle/Resources/config/services.yml
    #...
    services:
        web_hq_new.form.type.user:
            class: WebHQ\NewBundle\Form\Type\UserType
            tags:
                - { name: form.type, alias: user }
    #...
    

    祝你好运!

    【讨论】:

    • 感谢您的回答。实际上我还有一些问题,当我调用页面编辑/任务时,会出现以下警报:属性“user”和方法之一“getUser()”、“isUser()”、“hasUser()”、“ __get()” 存在并在“Acme\ManagementBundle\Entity\Mission”类中具有公共访问权限。我编辑了问题并展示了我的整个 Mission 实体。
    • 对不起,我打错了。在控制器中,editAction,将行 -&gt;add('user', 'user') 更改为 -&gt;add('users', 'user')。 “users”是一个属性名,“user”是一个表单类型。这应该可以解决错误。
    • 此外,您可以更改 FormType 参数,将其添加到控制器操作中的表单时。例如,如果你不想要求用户有相关的对象,字段不是必需的,你可以这样称呼它:-&gt;add('users', 'user', array('require' =&gt; false))
    • 很好,它有效。实际上,它与关联的用户创建了一个新任务;现在我正在尝试创建一个允许将现有任务与现有用户相关联的 editAction,但我正在阅读文档并且我认为我可以做到。如果我有问题,我会在这里评论。谢谢!
    • 好的,我已经为你添加了这两个动作。不同之处在于editAction 具有从路由传递的$id 参数。如果有{id} 参数通过,请检查您的路由文件。我已经包含了一个路由示例。
    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多