symfonyeventsfixturessubscriber

Do Subscribers work while loading Fixtures in Symfony?


I tried to run the fixture below on Symfony 5 using the command php bin/console d:f:l. I get this error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'contact_email' cannot be null

The same code logic is working fine for Post entities when creating them manually through the CRUD. Are fixtures not compatible with subscribers (events) or did i make a mistake?

Thank you.

Edit: I'm also using EasyAdmin Bundle 3.

App\DataFixtures.php\AppFixtures.php

<?php

namespace App\DataFixtures;

use App\Entity\User;
use App\Entity\Author;
use Doctrine\Persistence\ObjectManager;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class AppFixtures extends Fixture
{

    /** @var User[] */
    private $users = [];

    /** @var Author[] */
    private $authors = [];

    /** @var UserPasswordHasherInterface */
    private $hasher;

    public function __construct(UserPasswordHasherInterface $hasher)
    {
        $this->hasher = $hasher;
    }

    public function load(ObjectManager $manager): void
    {
        $this->createUsers();
        foreach($this->users as $user) $manager->persist($user);

        $this->createAuthors();
        foreach($this->authors as $author) $manager->persist($author);

        $manager->flush();
    }

    public function createUsers(): void
    {
        $admin = (new User)
            ->setUsername('admin')
            ->setEmail('admin@admin.com')
            ->setRoles(['ROLE_ADMIN'])
            ->setFirstname('Edouard')
            ->setLastname('Proust');
        $admin->setPassword($this->hasher->hashPassword($admin, 'admin'));

        $this->users[] = $admin;
    }

    public function createAuthors(): void
    {
        foreach($this->users as $user) {
            if(in_array('ROLE_ADMIN', $user->getRoles())) {
                $author = (new Author)
                    ->setUser($user)
                    ->setAvatar('#')
                    ->setBio('Bio')
                    // The line i want to get rid of:
                    // ->setContactEmail($user->getEmail())
                ;

                $this->authors[] = $author;
            }
        }
    }

}

App\EventListener\AuthorSubscriber.php

<?php

namespace App\EventListener;

use App\Entity\Author;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;

class AuthorSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return [
            BeforeEntityPersistedEvent::class => 'setContactEmail',
        ];
    }

    public function setContactEmail(BeforeEntityPersistedEvent $event)
    {
        
        /** @var Author */
        $entity = $event->getEntityInstance();
        if($entity instanceof Author) {
            if(!$entity->getContactEmail()) {
                $user = $entity->getUser();
                $contactEmail = $user ? $user->getEmail() : '#';
                $entity->setContactEmail($contactEmail);
            }
            
        }
    }

}

Solution

  • EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent:class is not proper Symfony event name. You probably should use Doctrine\ORM\Events::prePersist.

    Also please check your DoctrineBundle version. If you're using the default services.yaml configuration and DoctrineBundle lower than 2.1, you have to configure services.yaml with:

        App\EventListener\AuthorSubscriber:
            tags:
                - name: 'doctrine.event_subscriber'
    

    You can read something more here: https://symfony.com/doc/current/doctrine/events.html#doctrine-lifecycle-subscribers