@@ -665,7 +665,9 @@ the relationship between the removed ``Tag`` and ``Task`` object.
665
665
is handling the "update" of your Task::
666
666
667
667
// src/Acme/TaskBundle/Controller/TaskController.php
668
-
668
+
669
+ use Doctrine\Common\Collections\ArrayCollection;
670
+
669
671
// ...
670
672
public function editAction($id, Request $request)
671
673
{
@@ -676,11 +678,11 @@ the relationship between the removed ``Tag`` and ``Task`` object.
676
678
throw $this->createNotFoundException('No task found for is '.$id);
677
679
}
678
680
679
- $originalTags = array ();
681
+ $originalTags = new ArrayCollection ();
680
682
681
- // Create an array of the current Tag objects in the database
683
+ // Create an ArrayCollection of the current Tag objects in the database
682
684
foreach ($task->getTags() as $tag) {
683
- $originalTags[] = $tag;
685
+ $originalTags->add( $tag) ;
684
686
}
685
687
686
688
$editForm = $this->createForm(new TaskType(), $task);
@@ -689,27 +691,20 @@ the relationship between the removed ``Tag`` and ``Task`` object.
689
691
690
692
if ($editForm->isValid()) {
691
693
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
-
701
694
// remove the relationship between the tag and the Task
702
695
foreach ($originalTags as $tag) {
703
- // remove the Task from the Tag
704
- $tag->getTasks()->removeElement($task);
696
+ if (false === $task->getTags()->contains($tag)) {
697
+ // remove the Task from the Tag
698
+ $tag->getTasks()->removeElement($task);
705
699
706
- // if it were a many-to-one relationship, remove the relationship like this
707
- // $tag->setTask(null);
700
+ // if it was a many-to-one relationship, remove the relationship like this
701
+ // $tag->setTask(null);
708
702
709
- $em->persist($tag);
703
+ $em->persist($tag);
710
704
711
- // if you wanted to delete the Tag entirely, you can also do that
712
- // $em->remove($tag);
705
+ // if you wanted to delete the Tag entirely, you can also do that
706
+ // $em->remove($tag);
707
+ }
713
708
}
714
709
715
710
$em->persist($task);
0 commit comments