【发布时间】:2017-03-10 23:51:06
【问题描述】:
我有两个实体 - Book 和 Genre(多对多关系)。 图书实体:
/**
* @ORM\ManyToMany(targetEntity="Genre", mappedBy="books")
*/
private $genres;
流派实体:
/**
* @ORM\ManyToMany(targetEntity="Book", inversedBy="genres")
* @ORM\JoinTable(name="genres_books")
*/
private $books;
在我的 BookType 表单中,我想将这本书分配给多种类型(特定的书籍可以是犯罪和惊悚片或传记和历史等)。书籍类型:
->add('genres', EntityType::class, array(
'label' => 'Genres',
'class' => 'MyBundle:Genre',
'choice_label' => 'name',
'expanded' => true,
'multiple' => true,
'required' => false
));
设置者/获取者:
书
/**
* Add genres
*
* @param \MyBundle\Entity\Genre $genres
* @return Book
*/
public function addGenre(\MyBundle\Entity\Genre $genres)
{
$this->genres[] = $genres;
return $this;
}
/**
* Remove genres
*
* @param \MyBundle\Entity\Genre $genres
*/
public function removeGenre(\MyBundle\Entity\Genre $genres)
{
$this->genres->removeElement($genres);
}
/**
* Get genres
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getGenres()
{
return $this->genres;
}
类型
/**
* Add books
*
* @param \MyBundle\Entity\Book $books
* @return Genre
*/
public function addBook(\MyBundle\Entity\Book $books)
{
$this->books[] = $books;
return $this;
}
/**
* Remove books
*
* @param \MyBundle\Entity\Book $books
*/
public function removeBook(\MyBundle\Entity\Book $books)
{
$this->books->removeElement($books);
}
/**
* Get books
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getBooks()
{
return $this->books;
}
表单提交时没有任何错误(新书添加了除类型以外的所有值),但我无法建立关系 - 表单提交后,表genres_books 为空。怎么了?提前致谢。
编辑 - BookController:
/**
* Creates a new book entity.
*
* @Route("/new", name="book_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$book = new Book();
$form = $this->createForm('MyBundle\Form\BookType', $book);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->persist($book);
$this->getDoctrine()->getManager()->flush($book);
return $this->redirectToRoute('book_show', array('id' => $book->getId()));
}
return $this->render('book/new.html.twig', array(
'book' => $book,
'form' => $form->createView(),
));
}
【问题讨论】:
标签: forms symfony checkbox insert many-to-many