MergeCollectionListener.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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. */
  11. namespace Sonata\AdminBundle\Form\EventListener;
  12. use Symfony\Component\Form\FormEvent;
  13. use Symfony\Component\Form\FormEvents;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Sonata\AdminBundle\Model\ModelManagerInterface;
  16. class MergeCollectionListener implements EventSubscriberInterface
  17. {
  18. protected $modelManager;
  19. /**
  20. * @param \Sonata\AdminBundle\Model\ModelManagerInterface $modelManager
  21. */
  22. public function __construct(ModelManagerInterface $modelManager)
  23. {
  24. $this->modelManager = $modelManager;
  25. }
  26. /**
  27. * {@inheritDoc}
  28. */
  29. public static function getSubscribedEvents()
  30. {
  31. return array(
  32. FormEvents::SUBMIT => array('onBind', 10),
  33. );
  34. }
  35. /**
  36. * @param \Symfony\Component\Form\FormEvent $event
  37. */
  38. public function onBind(FormEvent $event)
  39. {
  40. $collection = $event->getForm()->getData();
  41. $data = $event->getData();
  42. // looks like there is no way to remove other listeners
  43. $event->stopPropagation();
  44. if (!$collection) {
  45. $collection = $data;
  46. } elseif (count($data) === 0) {
  47. $this->modelManager->collectionClear($collection);
  48. } else {
  49. // merge $data into $collection
  50. foreach ($collection as $entity) {
  51. if (!$this->modelManager->collectionHasElement($data, $entity)) {
  52. $this->modelManager->collectionRemoveElement($collection, $entity);
  53. } else {
  54. $this->modelManager->collectionRemoveElement($data, $entity);
  55. }
  56. }
  57. foreach ($data as $entity) {
  58. $this->modelManager->collectionAddElement($collection, $entity);
  59. }
  60. }
  61. $event->setData($collection);
  62. }
  63. }