I 'm having a form on which i can create a new "Book". For a book, i can add tags (e.g. to describe additional information about it).
The relation between Book and Tag is ManyToMany, because each Book can have many tags, and each tag can rely to different books. (Each tag is a unique field on its name). So, when a user enters a new tag to a book that does not exists in the database, i want to create the tag when submitting. If it already exists, i want to add the tag to the book. I've tried the following:
$book = $this->form->getData();
foreach ($tags as $tag) {
$tag = strtolower($tag);
// check if tag already exists
$tagEntity = $this->em->getRepository('BookBundle:Tag')->findByName($tag);
// if not, create new tag and add
if(null === $tagEntity)
{
$tagEntity = new Tag();
$tagEntity->setName($tag);
}
// add tag to book
$book->addTag($tagEntity);
// add book to tag
$tagEntity->addbook($book);
// create relation between tag and book
$this->em->persist($book);
$this->em->persist($tagEntity);
$this->em->flush();
}
Questions:
1) Do i first need to create the book after line 1 with persist and flush, before i can go on?
2) What is the best way to handle adding (new) tags to books, like I described above ?
At the moment when i click on "submit", my local apache does not respond and "hangs up"..
Regards