簡體   English   中英

訂閱者在 Symfony 中加載夾具時是否工作?

[英]Do Subscribers work while loading Fixtures in Symfony?

我嘗試使用命令php bin/console d:f:l在 Symfony 5 上運行下面的夾具。 我收到此錯誤: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'contact_email' cannot be null

通過 CRUD 手動創建 Post 實體時,相同的代碼邏輯可以正常工作。 固定裝置與訂閱者(事件)不兼容還是我犯了錯誤?

謝謝你。

編輯:我也在使用 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);
            }
            
        }
    }

}

EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent:class不是正確的 Symfony 事件名稱。 您可能應該使用Doctrine\ORM\Events::prePersist

另請檢查您的 DoctrineBundle 版本。 如果你使用默認的 services.yaml 配置和低於 2.1 的 DoctrineBundle,你必須配置services.yaml

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

你可以在這里閱讀更多內容: https://symfony.com/doc/current/doctrine/events.html#doctrine-lifecycle-subscribers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM