2017-03-10 12 views
0

私は2つのエンティティ(ブックとジャンル)を持っています(多対多の関係)。 ブックエンティティ:Symfony 2.8多対多のデー​​タベースに複数のチェックボックスを挿入する

/** 
* @ORM\ManyToMany(targetEntity="Genre", mappedBy="books") 
*/ 
private $genres; 

ジャンルエンティティ:私のブックタイプの形で

/** 
* @ORM\ManyToMany(targetEntity="Book", inversedBy="genres") 
* @ORM\JoinTable(name="genres_books") 
*/ 
private $books; 

私は多くのジャンルに本を割り当てる(特定の本が犯罪やスリラーや伝記や歴史または何でもすることができます)。ブックタイプ:

->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はフォームがサブミットされてから空です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(), 
    )); 
} 

答えて

1

あなたは関係の側面を所有して変更する必要があり、この設定ではジャンルを持続することができるようにします。

ブックエンティティ:

/** 
* @ORM\ManyToMany(targetEntity="Genre", inversedBy="books") 
* @ORM\JoinTable(name="genres_books") 
*/ 
private $genres; 

ジャンルエンティティ:symfonyの3.2.6

+0

作品でテスト

/** * @ORM\ManyToMany(targetEntity="Book", mappedBy="genres") */ private $books; 

!ありがとう! – Tompo

関連する問題