Saving current user id in repository

520 Views Asked by At

I try to save initial value for user field in UserService entity. The reason is, I use this entity in EasyAdminBundle and when I build a form, I want to set a default value for user_id (ManyToOne to User entity).

  • init entity manager in constructor,
  • I override save method.
  • I get user from security session context and set to user service object, persist and flush.

...but I still can't see a change during save.

class UserServiceRepository extends ServiceEntityRepository
{

protected $_em;

public function __construct(RegistryInterface $registry)
{

    $this->_em = $this->entityManager;

    parent::__construct($registry, UserService::class);
}

// I override save method:
public function save(UserService $userService)
{
    // Get current user from security:
    $user = $this->get('security.token_storage')->getToken()->getUser();
    // set to useService...
    $userService->setUser($user);

        // and persist & flush:
        $this->_em->persist($userService);
        $this->_em->flush();


}
1

There are 1 best solutions below

4
alvery On BEST ANSWER
// I override save method:

You're overriding non-existent method in parent, there's no save method in ServiceEntityRepository nor EntityRepository. So what's the main point of what you are doing and why you're setting default user_id in service repository?

UPDATE:

services:
    my.listener:
        class: UserServiceListener
        arguments:
            - "@security.token_storage"
        tags:
            - { name: doctrine.event_listener, event: prePersist }

Listener:

class UserServiceListener
{
    private $token_storage;

    public function __construct(TokenStorageInterface $token_storage)
    {
        $this->token_storage = $token_storage;
    }

    public function prePersist(LifeCycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if (!$entity instanceof UserService) {
           return;
        }

        $entity->setUser($this->token_storage->getToken()->getUser());
    }
}