Reputation: 263
I use the symfony 3 and try to get the current user data in Entity Repository file, but when i used $this->get('security.token_storage')->getToken()->getUser();
, there is a error message that is can not found the get function
So, how to do it?
PS: if in the form type, how to invoke the user data.
Thanks.
Upvotes: 2
Views: 9525
Reputation: 51
Since Symfony 3.4 you can use the security Utility Class. This allow you to retrieve the actual user.
use Symfony\Component\Security\Core\Security;
...
class YourRepository
{
private $security;
public function __construct(ManagerRegistry $registry, Security $security)
{
parent::__construct($registry, Projekt::class);
$this->security = $security;
}
public function findSomethingByUser(User $user)
{
$query = $this->getEntityManager()
->createQuery(
'SELECT t FROM AppBundle:Table t '.
'WHERE t.user > :user'
)->setParameter('user', $this->security->getUser());
return $query->getResult();
}
Upvotes: 2
Reputation: 21600
Repositories shouldnt known the user. If you need user information you should make a method like this:
class YourRepository
{
public function findSomethingByUser(User $user)
{
$query = $this->getEntityManager()
->createQuery(
'SELECT t FROM AppBundle:Table t '.
'WHERE t.user > :user'
)->setParameter('user', $user->getUsername());
return $query->getResult();
}
}
You can use the repository inside a controller:
class MyController
{
public function someAction()
{
$user = $this->get('security.token_storage')
->getToken()
->getUser();
$this->get('doctrine')
->getManager()
->getRepository('AppBundle:EntityName')
->findSomethingByUser($user);
return new Response('foo');
}
}
Upvotes: 4
Reputation: 109
Entity Repository has not Container. You can find solution how do it (as example here Symfony2: How to access to service from repository), but it is not best practice. Repositories have only one goal - work with data from the database. You can pass the user object as parameter for your method.
Upvotes: 0