MergeCollectionListener.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Form\EventListener;
  11. use Sonata\AdminBundle\Model\ModelManagerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\Form\FormEvent;
  14. use Symfony\Component\Form\FormEvents;
  15. /**
  16. * Class MergeCollectionListener.
  17. *
  18. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  19. */
  20. class MergeCollectionListener implements EventSubscriberInterface
  21. {
  22. protected $modelManager;
  23. /**
  24. * @param \Sonata\AdminBundle\Model\ModelManagerInterface $modelManager
  25. */
  26. public function __construct(ModelManagerInterface $modelManager)
  27. {
  28. $this->modelManager = $modelManager;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public static function getSubscribedEvents()
  34. {
  35. return array(
  36. FormEvents::SUBMIT => array('onBind', 10),
  37. );
  38. }
  39. /**
  40. * @param \Symfony\Component\Form\FormEvent $event
  41. */
  42. public function onBind(FormEvent $event)
  43. {
  44. $collection = $event->getForm()->getData();
  45. $data = $event->getData();
  46. // looks like there is no way to remove other listeners
  47. $event->stopPropagation();
  48. if (!$collection) {
  49. $collection = $data;
  50. } elseif (count($data) === 0) {
  51. $this->modelManager->collectionClear($collection);
  52. } else {
  53. // merge $data into $collection
  54. foreach ($collection as $entity) {
  55. if (!$this->modelManager->collectionHasElement($data, $entity)) {
  56. $this->modelManager->collectionRemoveElement($collection, $entity);
  57. } else {
  58. $this->modelManager->collectionRemoveElement($data, $entity);
  59. }
  60. }
  61. foreach ($data as $entity) {
  62. $this->modelManager->collectionAddElement($collection, $entity);
  63. }
  64. }
  65. $event->setData($collection);
  66. }
  67. }