SYMFONY 2.8多一对多插入DB多个复选框



我有两个实体 - 书籍和类型(许多关系)。书籍实体:

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

流派实体:

/**
* @ORMManyToMany(targetEntity="Book", inversedBy="genres")
* @ORMJoinTable(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           
    ));

setters/getters:

/**
 * Add genres
 *
 * @param MyBundleEntityGenre $genres
 * @return Book
 */
public function addGenre(MyBundleEntityGenre $genres)
{
    $this->genres[] = $genres;
    return $this;
}
/**
 * Remove genres
 *
 * @param MyBundleEntityGenre $genres
 */
public function removeGenre(MyBundleEntityGenre $genres)
{
    $this->genres->removeElement($genres);
}
/**
 * Get genres
 *
 * @return DoctrineCommonCollectionsCollection 
 */
public function getGenres()
{
    return $this->genres;
}

类型

/**
 * Add books
 *
 * @param MyBundleEntityBook $books
 * @return Genre
 */
public function addBook(MyBundleEntityBook $books)
{
    $this->books[] = $books;
    return $this;
}
/**
 * Remove books
 *
 * @param MyBundleEntityBook $books
 */
public function removeBook(MyBundleEntityBook $books)
{
    $this->books->removeElement($books);
}
/**
 * Get books
 *
 * @return DoctrineCommonCollectionsCollection 
 */
public function getBooks()
{
    return $this->books;
}

表格是在没有任何错误的情况下提交的(添加了新书,除了类型以外的所有值),但我无法建立关系 - 表格提交后,表格genres_book是空的。怎么了?提前致谢。

编辑 - 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('MyBundleFormBookType', $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(),
    ));
}

要能够在此设置中持久性流派,您必须更改关系的自有方面。

书籍实体:

/**
 * @ORMManyToMany(targetEntity="Genre", inversedBy="books")
 * @ORMJoinTable(name="genres_books")
 */
private $genres;

流派实体:

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

在Symfony 3.2.6

上测试

最新更新