Skip to content

Commit f4306ac

Browse files
author
Florian Körner
committed
Simplified "Ensuring the database persistence" example
1 parent 36ebcab commit f4306ac

File tree

1 file changed

+12
-19
lines changed

1 file changed

+12
-19
lines changed

cookbook/form/form_collections.rst

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -676,11 +676,11 @@ the relationship between the removed ``Tag`` and ``Task`` object.
676676
throw $this->createNotFoundException('No task found for is '.$id);
677677
}
678678

679-
$originalTags = array();
679+
$originalTags = new \Doctrine\Common\Collections\ArrayCollection();
680680

681-
// Create an array of the current Tag objects in the database
681+
// Create an ArrayCollection of the current Tag objects in the database
682682
foreach ($task->getTags() as $tag) {
683-
$originalTags[] = $tag;
683+
$originalTags->add($tag);
684684
}
685685

686686
$editForm = $this->createForm(new TaskType(), $task);
@@ -689,27 +689,20 @@ the relationship between the removed ``Tag`` and ``Task`` object.
689689

690690
if ($editForm->isValid()) {
691691

692-
// filter $originalTags to contain tags no longer present
693-
foreach ($task->getTags() as $tag) {
694-
foreach ($originalTags as $key => $toDel) {
695-
if ($toDel->getId() === $tag->getId()) {
696-
unset($originalTags[$key]);
697-
}
698-
}
699-
}
700-
701692
// remove the relationship between the tag and the Task
702693
foreach ($originalTags as $tag) {
703-
// remove the Task from the Tag
704-
$tag->getTasks()->removeElement($task);
694+
if ($task->getTags()->contains($tag) == false) {
695+
// remove the Task from the Tag
696+
$tag->getTasks()->removeElement($task);
705697

706-
// if it were a ManyToOne relationship, remove the relationship like this
707-
// $tag->setTask(null);
698+
// if it were a ManyToOne relationship, remove the relationship like this
699+
// $tag->setTask(null);
708700

709-
$em->persist($tag);
701+
$em->persist($tag);
710702

711-
// if you wanted to delete the Tag entirely, you can also do that
712-
// $em->remove($tag);
703+
// if you wanted to delete the Tag entirely, you can also do that
704+
// $em->remove($tag);
705+
}
713706
}
714707

715708
$em->persist($task);

0 commit comments

Comments
 (0)