MergeCollectionListener.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\Events;
  13. use Symfony\Component\Form\Event\FilterDataEvent;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Sonata\AdminBundle\Model\ModelManagerInterface;
  16. class MergeCollectionListener implements EventSubscriberInterface
  17. {
  18. protected $modelManager;
  19. public function __construct(ModelManagerInterface $modelManager)
  20. {
  21. $this->modelManager = $modelManager;
  22. }
  23. public static function getSubscribedEvents()
  24. {
  25. return Events::onBindNormData;
  26. }
  27. public function onBindNormData(FilterDataEvent $event)
  28. {
  29. $collection = $event->getForm()->getData();
  30. $data = $event->getData();
  31. if (!$collection) {
  32. $collection = $data;
  33. } else if (count($data) === 0) {
  34. $this->modelManager->collectionClear($collection);
  35. } else {
  36. // merge $data into $collection
  37. foreach ($collection as $entity) {
  38. if (!$this->modelManager->collectionHasElement($data, $entity)) {
  39. $this->modelManager->collectionRemoveElement($collection, $entity);
  40. } else {
  41. $this->modelManager->collectionRemoveElement($data, $entity);
  42. }
  43. }
  44. foreach ($data as $entity) {
  45. $this->modelManager->collectionAddElement($collection, $entity);
  46. }
  47. }
  48. $event->setData($collection);
  49. }
  50. }