I wanted to set password automatically when one register the form. So I use REGISTRATION_INITIALIZE to trigger the event. Unfortunately it's not working.
Listener:
<?php
namespace Acme\UserBundle\EventListener;
use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class RegistrationListener implements EventSubscriberInterface
{
/**
* #var EntityManager
*/
private $em;
/**
* #param \Doctrine\ORM\EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* {#inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit',
);
}
public function onRegistrationInit(UserEvent $userEvent)
{
$user = $userEvent->getUser();
$user->setPassword('abcdeffffff');
}
Services:
#src/Acme/UserBundle/Resources/config/services.yml
services:
acme_user.registration:
class: Acme\UserBundle\EventListener\RegistrationListener
arguments:
entityManager: "#doctrine.orm.entity_manager"
tags:
- { name: kernel.event_subscriber}
So the password is not setting and it shows the password should not be blank.
What am I doing wrong? Any help!
EDIT:
The problem was I was defining service at the wrong place.
Instead of src/Acme/UserBundle/Resources/config/services.yml, It should be app/config/services.yml.
I saw src/Acme/UserBundle/Resources/config/services.ymlin http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html, But was not working for me!
Maybe I am wrong, but I think your service definition uses features from Symfony 3.3 but you are using Symfony 3.2.8, e.g.
New in version 3.3: The ability to configure an argument by its name ($adminEmail) was added in Symfony 3.3. Previously, you could configure it only by its index (2 in this case) or by using empty quotes for the other arguments.
Try updating your service definition to:
#src/Acme/UserBundle/Resources/config/services.yml
services:
acme_user.registration:
class: Acme\UserBundle\EventListener\RegistrationListener
arguments: ["#doctrine.orm.entity_manager"]
tags:
- { name: kernel.event_subscriber}
And a remark: as you are actually using a subscriber you should rename the class RegistrationListener to RegistrationSubscriber.
Related
I have setup service to controller function like this
App\Controller\Controller:
calls:
- [new, ['#request_stack','#doctrine.orm.default_entity_manager']]
I needed Entity Manager inside controller action and my function looks like this
public function new(RequestStack $request, EntityManager $em): Response
{
$currentRequest = $request->getCurrentRequest();
$data = json_decode($currentRequest->getContent(), true);
....
return new ApiResponse(['message' => $message['message'], 'body' => 'success']);
}
and when executing comes to line return new ApiResponse it gives error
Controller "Controller::new()" requires that you provide a value for the "$request" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
How to get entity manager in controller action or how to resolve this problem?
As the Symfony 4 Doc on Doctrine says :
// you can fetch the EntityManager via $this->getDoctrine()
// or you can add an argument to your action: index(EntityManagerInterface $entityManager)
$entityManager = $this->getDoctrine()->getManager();
So you can just get the entity manager this way in your controller
However, you can also register the Entity Manager as a service to use it.
Be sure to set the autowire to true :
# config/services.yaml
services:
_defaults:
autowire: true
and register it as a service :
# config/services.yaml
services:
#....
controller_em:
class: App\Controller\Controller
arguments: [ '#doctrine.orm.default_entity_manager' ]
public: true
So that you can use it like so in your controller :
private $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
You can also use this way to use the Entity Manager in Voter or Manager.
well. you need to inject your stuff into controller's object constructor - that is called DI in Symfony-way (or via set-methods):
services.yml - if everything ok with your autowire
App\Controller\Controller:
calls:
- [new]
if not add it manually:
App\Controller\Controller:
arguments:
- '#doctrine.orm.default_entity_manager'
calls:
- [new]
Controller.php
/** #var EntityManager */
private $em;
public __construct(EntityManager $em)
{
$this->em = $em;
}
and then just use it in your method:
public function new(RequestStack $request): Response
{
$this->em ...
}
For your information you can create your own AbsractController to inject the EntityManager in all controller extending it like this.
<?php
namespace App\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseController;
abstract class AbstractController extends BaseController
{
/**
* #var EntityManagerInterface
*/
protected $em;
/**
* #required
*
* #param EntityManagerInterface $em
*/
public function setEntityManager(EntityManagerInterface $em)
{
$this->em = $em;
}
}
If a controller extends this AbstractController, you could access $this->em everywhere in it.
The "required" annotation here is the key to enable what you tried to do without the need of adding configuration as you did. It's like adding a calls line in your configuration!
You could do something like this for every services you need in all your controllers.
I am developing a application with symfony2. Im facing a problem with localization. I want to set the in the postLoad event in doctrine lifecycle, but can find a way to do that. I am using the route method to set my local for example:
http://example.com/en/content
here is my listener:
namespace MyApiBundle\Listener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
class LocaleListener
{
private $local;
public function __construct($local) {
$this->local = $local;
}
public function postLoad(LifecycleEventArgs $args)
{
$local= 'en'; // I need to get the local from here
$entity = $args->getEntity();
if(method_exists($entity, 'setLocale')) {
$entity->setLocale($local);
}
}
}
Is there any quick way get the local from here? Cant use the new Request() as it always returning the en I also have 3 other language. Thanks for help
Yes, you can. You can inject #request_stack service into your listener, get request from it and read locale.
There is, however, a Doctrine extension that probably does what you want: Translatable
Thanks #Igor Pantovic
here I got it work, here is my local listner:
#/src/MyApiBUndle/Listner/LocalListner.php
namespace MyApiBundle\Listener;
use Symfony\Component\HttpFoundation\RequestStack;
use Doctrine\ORM\Event\LifecycleEventArgs;
class LocaleListener {
private $requestStack;
/**
* #param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack) {
$this->requestStack = $requestStack;
}
/**
* #param LifecycleEventArgs $args
*/
public function postLoad(LifecycleEventArgs $args)
{
$local= $this->requestStack->getCurrentRequest()->getLocale();
$entity = $args->getEntity();
if(method_exists($entity, 'setLocale')) {
$entity->setLocale($local);
}
}
}
and my service
services:
my_api.listener.locale_listener:
class: MyApiBundle\Listener\LocaleListener
tags:
- { name: doctrine.event_listener, event: postLoad }
# #request_stack must be quoted "":
arguments: ["#request_stack"]
hope this will help other too
I am trying to use a custom UserProvider with the FOS User bundle package and the FOS Oauth package. I have been following this tutorial http://blog.tankist.de/blog/2013/07/17/oauth2-explained-part-2-setting-up-oauth2-with-symfony2-using-fosoauthserverbundle/.
When I try and register my new user service I am getting the following error
UserProvider::__construct() must implement interface Doctrine\Common\Persistence\ObjectRepository, array given
UserProvider:
UserProvider implements UserProviderInterface
{
/**
* #var ObjectRepository
*/
protected $userRepository;
/**
* #param ObjectRepository $userRepository
*/
public function __construct(ObjectRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* #param string $username
* #return mixed
*/
public function loadUserByUsername($username)
{ ... }
UserRepository
class UserRepository extends EntityRepository implements ObjectRepository
services.yml
parameters:
entity_name: Hornby\UserBundle\Entity\UserRepository
services:
user_provider_me:
class: Hornby\UserBundle\Provider\UserProvider
arguments:
name: [%entity_name%]
Your services.yml file is wrong. I'm not really sure what you want to achieve but you pass array
arguments:
name: [%entity_name%] #entity_name is just a string
as an argument to UserProvider class. Constructor of this class expects ObjectRepository and this is your problem here.
A translation of services.xml from link you provided should look rather like that:
parameters:
platform.entity.user.class: Acme\DemoBundle\Entity\User
platform.user.provider.class: Acme\DemoBundle\Provider\UserProvider
services:
platform.user.manager:
class: Doctrine\ORM\EntityManager
factory: ["#doctrine", getManagerForClass]
arguments: [%platform.entity.user.class%]
platform.user.repository:
class: Acme\DemoBundle\Repository\UserRepository
factory: ["#platform.user.manager", getRepository]
arguments: [%platform.entity.user.class%]
platform.user.provider:
class: %platform.user.provider.class%
arguments: [#platform.user.repository]
I've created my own service and I need to inject doctrine EntityManager, but I don't see that __construct() is called on my service, and injection doesn't work.
Here is the code and configs:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManager;
class UserService {
/**
*
* #var EntityManager
*/
protected $em;
public function __constructor(EntityManager $entityManager)
{
var_dump($entityManager);
exit(); // I've never saw it happen, looks like constructor never called
$this->em = $entityManager;
}
public function getUser($userId){
var_dump($this->em ); // outputs null
}
}
Here is services.yml in my bundle
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments:
entityManager: "#doctrine.orm.entity_manager"
I've imported that .yml in config.yml in my app like that
imports:
# a few lines skipped, not relevant here, i think
- { resource: "#TestCommonBundle/Resources/config/services.yml" }
And when I call service in controller
$userservice = $this->get('test.common.userservice');
$userservice->getUser(123);
I get an object (not null), but $this->em in UserService is null, and as I already mentioned, constructor on UserService has never been called
One more thing, Controller and UserService are in different bundles (I really need that to keep project organized), but still: everyting else works fine, I can even call
$this->get('doctrine.orm.entity_manager')
in same controller that I use to get UserService and get valid (not null) EntityManager object.
Look like that I'm missing piece of configuration or some link between UserService and Doctrine config.
Your class's constructor method should be called __construct(), not __constructor():
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "#doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your specific case, original code with tuning would look like this:
1. Use in your services or Controller
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class UserService
{
private $userRepository;
// use custom repository over direct use of EntityManager
// see step 2
public function __constructor(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function getUser($userId)
{
return $this->userRepository->find($userId);
}
}
2. Create new custom repository
<?php
namespace Test\CommonBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
class UserRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(UserEntity::class);
}
public function find($userId)
{
return $this->repository->find($userId);
}
}
3. Register services
# app/config/services.yml
services:
_defaults:
autowire: true
Test\CommonBundle\:
resource: ../../Test/CommonBundle
I setup a listener class where i'll set the ownerid column on any doctrine prePersist. My services.yml file looks like this ...
services:
my.listener:
class: App\SharedBundle\Listener\EntityListener
arguments: ["#security.context"]
tags:
- { name: doctrine.event_listener, event: prePersist }
and my class looks like this ...
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\SecurityContextInterface;
class EntityListener
{
protected $securityContext;
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
*
* #param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
$entity->setCreatedby();
}
}
The result of this is the following error.
ServiceCircularReferenceException: Circular reference detected for service "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> my.listener -> security.context -> security.authentication.manager -> fos_user.user_manager".
My assumption is that the security context has already been injected somewhere in the chain but I don't know how to access it. Any ideas?
I had similar problems and the only workaround was to pass the whole container in the constructor (arguments: ['#service_container']).
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
// ...
public function prePersist(LifeCycleEventArgs $args)
{
$securityContext = $this->container->get('security.context');
// ...
}
}
As of Symfony 2.6 this issue should be fixed. A pull request has just been accepted into the master. Your problem is described in here.
https://github.com/symfony/symfony/pull/11690
As of Symfony 2.6, you can inject the security.token_storage into your listener. This service will contain the token as used by the SecurityContext in <=2.5. In 3.0 this service will replace the SecurityContext::getToken() altogether. You can see a basic change list here: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service
Example usage in 2.6:
Your configuration:
services:
my.entityListener:
class: App\SharedBundle\Listener\EntityListener
arguments:
- "#security.token_storage"
tags:
- { name: doctrine.event_listener, event: prePersist }
Your Listener
namespace App\SharedBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class EntityListener
{
private $token_storage;
public function __construct(TokenStorageInterface $token_storage)
{
$this->token_storage = $token_storage;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entity->setCreatedBy($this->token_storage->getToken()->getUsername());
}
}
For a nice created_by example, you can use https://github.com/hostnet/entity-blamable-component/blob/master/src/Listener/BlamableListener.php for inspiration. It uses the hostnet/entity-tracker-component which provides a special event that is fired when an entity is changed during your request. There's also a bundle to configure this in Symfony2
https://github.com/hostnet/entity-tracker-component
https://github.com/hostnet/entity-tracker-bundle
There's a great answer already in this thread but everything changes. Now there're entity listeners classes in Doctrine:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners-class
So you can add an annotation to your entity like:
/**
* #ORM\EntityListeners({"App\Entity\Listener\PhotoListener"})
* #ORM\Entity(repositoryClass="App\Repository\PhotoRepository")
*/
class Photo
{
// Entity code here...
}
And create a class like this:
class PhotoListener
{
private $container;
function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/** #ORM\PreRemove() */
public function preRemoveHandler(Photo $photo, LifecycleEventArgs $event): void
{
// Some code here...
}
}
Also you should define this listener in services.yml like that:
photo_listener:
class: App\Entity\Listener\PhotoListener
public: false
autowire: true
tags:
- {name: doctrine.orm.entity_listener}
I use the doctrine config files to set preUpdate or prePersist methods:
Project\MainBundle\Entity\YourEntity:
type: entity
table: yourentities
repositoryClass: Project\MainBundle\Repository\YourEntitytRepository
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
lifecycleCallbacks:
prePersist: [methodNameHere]
preUpdate: [anotherMethodHere]
And the methods are declared in the entity, this way you don't need a listener and if you need a more general method you can make a BaseEntity to keep that method and extend the other entites from that. Hope it helps!
Symfony 6.2.4
Add this in your Entity :
#[ORM\EntityListeners(["App\Doctrine\MyListener"])]
Add this in your services.yaml:
App\Doctrine\MyListener:
tags: [doctrine.orm.entity_listener]
Then you can do this :
<?php
namespace App\Doctrine;
use App\Entity\MyEntity;
use Symfony\Component\Security\Core\Security;
class MyListener
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function prePersist(MyEntity $myEntity)
{
//Your stuff
}
}
Hope it helps.