MergeCollectionListener.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\FormEvents;
  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. /**
  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(FormEvents::BIND => 'onBind');
  32. }
  33. /**
  34. * @param \Symfony\Component\Form\Event\FilterDataEvent $event
  35. */
  36. public function onBind(FilterDataEvent $event)
  37. {
  38. $collection = $event->getForm()->getData();
  39. $data = $event->getData();
  40. if (!$collection) {
  41. $collection = $data;
  42. } else if (count($data) === 0) {
  43. $this->modelManager->collectionClear($collection);
  44. } else {
  45. // merge $data into $collection
  46. foreach ($collection as $entity) {
  47. if (!$this->modelManager->collectionHasElement($data, $entity)) {
  48. $this->modelManager->collectionRemoveElement($collection, $entity);
  49. } else {
  50. $this->modelManager->collectionRemoveElement($data, $entity);
  51. }
  52. }
  53. foreach ($data as $entity) {
  54. $this->modelManager->collectionAddElement($collection, $entity);
  55. }
  56. }
  57. $event->setData($collection);
  58. }
  59. }