0
我有兩個實體 - Book和Genre(多對多關係)。 Book實體:Symfony 2.8多對多插入db多選框
/**
* @ORM\ManyToMany(targetEntity="Genre", mappedBy="books")
*/
private $genres;
類型的實體:
/**
* @ORM\ManyToMany(targetEntity="Book", inversedBy="genres")
* @ORM\JoinTable(name="genres_books")
*/
private $books;
在我的BookType的形式我想分配的書很多的流派(特別是本書可犯罪和驚悚片或傳記和歷史或其他)。的BookType:
->add('genres', EntityType::class, array(
'label' => 'Genres',
'class' => 'MyBundle:Genre',
'choice_label' => 'name',
'expanded' => true,
'multiple' => true,
'required' => false
));
二傳手/ getter方法:
書
/**
* 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;
}
的形式沒有任何錯誤(這本新書加入除了所有的值提交類型),但我無法建立關係 - 在表單是subm之後,表genres_books是空的itted。怎麼了?提前致謝。
編輯 - 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(),
));
}
作品!謝謝 ! – Tompo