How to disable soft delete (Soft-deleteable) filter for doctrine in symfony

前端 未结 4 1697
梦如初夏
梦如初夏 2021-02-19 15:55

Installing and using SoftDeleteable behavior extension for Doctrine 2 is quite easy. The problem usually is trying to disable it for some code part and enabling again. You may w

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-19 16:15

    You can use a service to disable and reenable the soft delete filter behaviour:

    getEventManager()->getListeners() as $eventName => $listeners) {
                foreach ($listeners as $listener) {
                    if ($listener instanceof SoftDeleteableListener) {
                        if ($eventName === self::EVENT_NAME) {
                            $this->originalEventListener = $listener;
                            $em->getEventManager()->removeEventListener($eventName, $listener);
                        }
                    }
                }
            }
        }
    
        /**
         * @param EntityManagerInterface $em
         */
        public function undoRemoveSoftDeleteFilter(EntityManagerInterface $em)
        {
            if (empty($this->originalEventListener)) {
                throw new \Exception('can not undo remove, soft delete listener was not removed');
            }
            // re-add the removed listener back to the event-manager
            $em->getEventManager()->addEventListener(self::EVENT_NAME, $this->originalEventListener);
        }
    }
    

    usage:

    $this->softDeleteFilter->removeSoftDeleteFilter($this->entityManager);
    $this->entityManager->remove($entity);
    $this->entityManager->flush();
    $this->softDeleteFilter->undoRemoveSoftDeleteFilter($this->entityManager);
    

提交回复
热议问题