MergeCollectionListener.php 2.0 KB

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