12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?php
- /*
- * This file is part of the Sonata package.
- *
- * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- *
- */
- namespace Sonata\AdminBundle\Form\EventListener;
- use Symfony\Component\Form\Events;
- use Symfony\Component\Form\Event\FilterDataEvent;
- use Symfony\Component\EventDispatcher\EventSubscriberInterface;
- use Sonata\AdminBundle\Model\ModelManagerInterface;
- class MergeCollectionListener implements EventSubscriberInterface
- {
- protected $modelManager;
- public function __construct(ModelManagerInterface $modelManager)
- {
- $this->modelManager = $modelManager;
- }
- public static function getSubscribedEvents()
- {
- return Events::onBindNormData;
- }
- public function onBindNormData(FilterDataEvent $event)
- {
- $collection = $event->getForm()->getData();
- $data = $event->getData();
- if (!$collection) {
- $collection = $data;
- } else if (count($data) === 0) {
- $this->modelManager->collectionClear($collection);
- } else {
- // merge $data into $collection
- foreach ($collection as $entity) {
- if (!$this->modelManager->collectionHasElement($data, $entity)) {
- $this->modelManager->collectionRemoveElement($collection, $entity);
- } else {
- $this->modelManager->collectionRemoveElement($data, $entity);
- }
- }
- foreach ($data as $entity) {
- $this->modelManager->collectionAddElement($collection, $entity);
- }
- }
- $event->setData($collection);
- }
- }
|