I have registered the following listener as a service. This saves the logged-in-user. It works perfectly. After saving the entity the user-id is in createdBy and updatedBy. Ok a little problem: The command "php app / console doctrine: fixtures: load" throws the error "Call to a member function getUser () on a non-object. That's kind of understandable. Only now do I have to disable every time the service before? Do you have another solution?
class UserListener implements EventSubscriber { protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function getSubscribedEvents() { return array( Events::prePersist, Events::preUpdate ); } public function prePersist(LifecycleEventArgs $args) { $entity = $args->getEntity(); if ($entity instanceof Post) { $user = $this->container->get('security.context')->getToken()->getUser(); if (!is_object($user) || !$user instanceof User) { throw new AccessDeniedException(); } $entity->setCreatedBy($user); $entity->setUpdatedBy($user); } } /** * @param PreUpdateEventArgs $args */ public function preUpdate(PreUpdateEventArgs $args) { $entity = $args->getEntity(); $em = $args->getEntityManager(); if ($entity instanceof Post) { $user = $this->container->get('security.context')->getToken()->getUser(); if (!is_object($user) || !$user instanceof User) { throw new AccessDeniedException(); } $entity->setUpdatedBy($user); $uow = $em->getUnitOfWork(); $meta = $em->getClassMetadata(get_class($entity)); $uow->recomputeSingleEntityChangeSet($meta, $entity); } } }