Symfony2如何将2个实体添加到1个表单类型

时间:2015-07-16 11:41:04

标签: php forms symfony checkbox entity

我有2个实体,Tour和Destination,就像这样

游:

<?php

namespace HearWeGo\HearWeGoBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Tour
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="HearWeGo\HearWeGoBundle\Entity\Repository\TourRepository")
 */
class Tour
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     * @Assert\NotBlank(message="This field must be filled")
     * 
     */
    private $name;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="startdate", type="datetime")
     * @Assert\DateTime()
     */
    private $startdate;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="enddate", type="datetime")
     * @Assert\DateTime()
     */
    private $enddate;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="boolean")
     */
    private $status;

    /**
     * @var integer
     *
     * @ORM\Column(name="discount", type="integer")
     */
    private $discount;

    /**
     * @var string
     *
     * @ORM\Column(name="info", type="text")
     * @Assert\NotBlank(message="This field must be filled")
     * 
     */
    private $info;

    /**
     * @ORM\ManyToOne(targetEntity="HearWeGo\HearWeGoBundle\Entity\Company", inversedBy="tours")
     */
    private $company;

    /**
     * @ORM\ManyToMany(targetEntity="HearWeGo\HearWeGoBundle\Entity\Destination", mappedBy="tours")
     * @Assert\NotBlank(message="This field must be filled")
     * 
     */
    private $destinations;

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

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

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

        return $this;
    }

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

    /**
     * Set startdate
     *
     * @param \DateTime $startdate
     * @return Tour
     */
    public function setStartdate($startdate)
    {
        $this->startdate = $startdate;

        return $this;
    }

    /**
     * Get startdate
     *
     * @return \DateTime 
     */
    public function getStartdate()
    {
        return $this->startdate;
    }

    /**
     * Set enddate
     *
     * @param \DateTime $enddate
     * @return Tour
     */
    public function setEnddate($enddate)
    {
        $this->enddate = $enddate;

        return $this;
    }

    /**
     * Get enddate
     *
     * @return \DateTime 
     */
    public function getEnddate()
    {
        return $this->enddate;
    }

    /**
     * Set status
     *
     * @param string $status
     * @return Tour
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

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

    /**
     * Set discount
     *
     * @param integer $discount
     * @return Tour
     */
    public function setDiscount($discount)
    {
        $this->discount = $discount;

        return $this;
    }

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

    /**
     * Set info
     *
     * @param string $info
     * @return Tour
     */
    public function setInfo($info)
    {
        $this->info = $info;

        return $this;
    }

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

    /**
     * Set company
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Company $company
     * @return Tour
     */
    public function setCompany(\HearWeGo\HearWeGoBundle\Entity\Company $company = null)
    {
        $this->company = $company;

        return $this;
    }

    /**
     * Get company
     *
     * @return \HearWeGo\HearWeGoBundle\Entity\Company 
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * Add destinations
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Destination $destinations
     * @return Tour
     */
    public function addDestination(\HearWeGo\HearWeGoBundle\Entity\Destination $destinations)
    {
        $this->destinations[] = $destinations;

        return $this;
    }

    /**
     * Remove destinations
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Destination $destinations
     */
    public function removeDestination(\HearWeGo\HearWeGoBundle\Entity\Destination $destinations)
    {
        $this->destinations->removeElement($destinations);
    }

    /**
     * Get destinations
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getDestinations()
    {
        return $this->destinations;
    }

}

目的地:

<?php

namespace HearWeGo\HearWeGoBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Destination
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="HearWeGo\HearWeGoBundle\Entity\Repository\DestinationRepository")
 */
class Destination
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     * @Assert\NotBlank(message="This field must be filled")
     * 
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="location", type="decimal")
     */
    private $location;

    /**
     * @ORM\OneToMany(targetEntity="HearWeGo\HearWeGoBundle\Entity\Audio", mappedBy="destination")
     */
    private $audio;

    /**
     * @ORM\OneToMany(targetEntity="HearWeGo\HearWeGoBundle\Entity\Article", mappedBy="destination")
     */
    private $articles;


    /**
     * @ORM\ManyToMany(targetEntity="HearWeGo\HearWeGoBundle\Entity\Tour", inversedBy="destinations")
     * @ORM\JoinTable(name="tours_destinations")
     */
    private $tours;

    function __construct()
    {
        $this->article = new ArrayCollection();
        $this->tours = new ArrayCollection();
    }

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

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

        return $this;
    }

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

    /**
     * Set location
     *
     * @param string $location
     * @return Destination
     */
    public function setLocation($location)
    {
        $this->location = $location;

        return $this;
    }

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

    /**
     * Add audio
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Audio $audio
     * @return Destination
     */
    public function addAudio(\HearWeGo\HearWeGoBundle\Entity\Audio $audio)
    {
        $this->audio[] = $audio;

        return $this;
    }

    /**
     * Remove audio
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Audio $audio
     */
    public function removeAudio(\HearWeGo\HearWeGoBundle\Entity\Audio $audio)
    {
        $this->audio->removeElement($audio);
    }

    /**
     * Get audio
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getAudio()
    {
        return $this->audio;
    }

    /**
     * Add articles
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Article $articles
     * @return Destination
     */
    public function addArticle(\HearWeGo\HearWeGoBundle\Entity\Article $articles)
    {
        $this->articles[] = $articles;

        return $this;
    }

    /**
     * Remove articles
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Article $articles
     */
    public function removeArticle(\HearWeGo\HearWeGoBundle\Entity\Article $articles)
    {
        $this->articles->removeElement($articles);
    }

    /**
     * Get articles
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getArticles()
    {
        return $this->articles;
    }

    /**
     * Add tours
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Tour $tours
     * @return Destination
     */
    public function addTour(\HearWeGo\HearWeGoBundle\Entity\Tour $tours)
    {
        $this->tours[] = $tours;

        return $this;
    }

    /**
     * Remove tours
     *
     * @param \HearWeGo\HearWeGoBundle\Entity\Tour $tours
     */
    public function removeTour(\HearWeGo\HearWeGoBundle\Entity\Tour $tours)
    {
        $this->tours->removeElement($tours);
    }

    /**
     * Get tours
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getTours()
    {
        return $this->tours;
    }
}

表单类型I构建如下

<?php

namespace HearWeGo\HearWeGoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CompanySubmitTourType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name','text')
            ->add('startdate','datetime')
            ->add('enddate','datetime')
            ->add('discount','number')
            ->add('info','text')
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('data_class'=>"HearWeGo\HearWeGoBundle\Entity\Tour"));
    }

    public function getName()
    {
        return 'company_submit_tour';
    }
}

在处理它的控制器

/**
     * @Route("/company/submit",name="company_submit")
     */
    public function submitTourAction(Request $request)
    {
        $tour=new Tour();
        $form=$this->createForm(new CompanySubmitTourType(),$tour,array('method'=>'POST','action'=>$this->generateUrl('company_submit')));
        $repository=$this->getDoctrine()->getRepository('HearWeGoHearWeGoBundle:Destination')->findAll();
        $dest_arr=array();
        $form_check=$this->createFormBuilder($dest_arr,array('method'=>'POST','action'=>$this->generateUrl('company_submit')));
        $i=0;
        foreach ($repository as $item)
        {
            $i++;
            $form_check->add('destination','checkbox',array('label'=>$item->getName()));
        }
        $form_check->add('submit','submit');
        $form->handleRequest($request);
        if ($request->getMethod()=='POST')
        {
            if ($form->isValid())
            {
                $em=$this->getDoctrine()->getEntityManager();

                $em->persist($tour);
                $em->flush();
                return new Response("<html>".$tour->getName()." has been created!</html>");
            }
        }
        return $this->render('HearWeGoHearWeGoBundle:Company:companySubmit.html.twig',array('form1'=>$form->createView(),'form2'=>$form_check->getForm()->createView()));
    }

如您所见,我必须使用两种形式: $form用于将数据持久保存到Tour实体 $form_check用于获取我数据库中Destination表中所有记录的列表,然后显示复选框,供用户选择多个目标选项 我希望当用户点击“提交”按钮时,在我的数据库的Tour表中创建一个新记录,并且已检查的Destination对象列表也在数据中保持不变 但是2个表单不能一次发送POST方法 我没有在CompanySubmitTourType中添加所有记录的名称是徒劳的,所以我现在不知道该怎么做,即使我将此行添加到表单类型

->add('destinations','entity',array('class'=>'HearWeGoHearWeGoBundle:Destination','property'=>'name'))

然后在Controller中用循环中的$form_check->add替换$form->add,它只显示一个下拉菜单,其中我只能选择一个,而不是像我想要的那样选择多个选项。所以请帮我解决。我想使用复选框允许用户选择多个选项

0 个答案:

没有答案