0

I would like to show on EasyAdmin a custom property, here is an example :

class Book
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    public $id;
    /**
     * @ORM\Column(type="string")
     */
    public $name;
    /**
     * @ORM\Column(type="float")
     */
    public $price;
    public function getBenefit(): float
    {
        // Here the method to retrieve the benefits
    }
}

In this example, the custom parameter is benefit it's not a parameter of our Entity and if we configure EasyAdmin like that, it works !

easy_admin:
    entities:
        Book:
            class: App\Entity\Book
            list:
                fields:
                    - { property: 'title', label: 'Title' }
                    - { property: 'benefit', label: 'Benefits' }

The problem is if the function is a bit complexe and need for example an EntityRepository, it becomes impossible to respect Controller > Repository > Entities.

Does anyone have a workaround, maybe by using the AdminController to show custom properties properly in EasyAdmin ?

4

1 回答 1

1

您不应该将检索收益的逻辑放在Book实体内部,尤其是当它涉及外部依赖项时,例如entityManager.

您可能可以使用 Doctrine 事件来实现这一点。Book从数据库加载实体后检索收益。Book在将实体保存在数据库中之前或之后保存收益。

你可以在这里找到更多关于它的信息https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html

class Book
{
    ...
    public $benefits;
}
// src/EventListener/RetrieveBenefitListener.php
namespace App\EventListener;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use App\Entity\Book;

class RetrieveBenefitListener
{
    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        // only act on some "Book" entity
        if (!$entity instanceof Book) {
            return;
        }

        // Your logic to retrieve the benefits
        $entity->benefits = methodToGetTheBenefits();
    }
}
// src/EventListener/SaveBenefitListener.php
namespace App\EventListener;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use App\Entity\Book;

class SaveBenefitListener
{
    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        // only act on some "Book" entity
        if (!$entity instanceof Book) {
            return;
        }

        // Your logic to save the benefits
        methodToSaveTheBenefits($entity->benefits);
    }
}
// services.yml
services:
    App\EventListener\RetrieveBenefitListener:
        tags:
            - { name: doctrine.event_listener, event: postLoad }
    App\EventListener\SaveBenefitListener:
        tags:
            - { name: doctrine.event_listener, event: postUpdate }

这只是一个例子,我没有测试过代码。postPersist如果您创建新Book对象,您可能必须为事件添加逻辑。

根据检索收益的逻辑(另一个数据库调用?从外部 API 加载?),您可能希望以不同的方式解决问题(缓存、通过 cron 作业将它们加载到您的数据库中,...)

于 2019-03-21T10:20:14.353 回答