The Blog

Symfony2 Doctrin2 encode password using prePersist Event Listener Posted on

Service needs to look like this

        class: AppBundle\EventListener\UserListener
        arguments: [ "@security.password_encoder" ]
        tags: [ { name: doctrine.event_listener, event: prePersist } ]

Listener should look like that

// AppBundle\EventListener\UserListener.php

namespace AppBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserListener
    protected $container;

    public function __construct(UserPasswordEncoderInterface $encoder)
        $this->encoder = $encoder;

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

        $encodedPassword = $this->encoder->encodePassword($entity, $entity->getPassword());
This entry was posted in Symfony3. Bookmark the permalink.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

Change the CAPTCHA codeSpeak the CAPTCHA code