在 Sonata Admin 列表视图中显示不同的实体

Showing different entities in Sonata Admin list view

我有这个实体,其中包含 entityName 属性 和 entityId 属性:

    /**
     * @var string
     *
     * @ORM\Column(name="entityName", type="string", length=255)
     */
    private $entityName;

    /**
     * @var integer
     * @ORM\Column(name="entityId", type="integer")
     */
    private $entityId;

我没有使用 __toString() 函数显示此实体,而是想 return 具有名称和 ID 的实体。并在奏鸣曲管理列表视图中显示。

现在,这里是 __toString:

public function __toString()
{
    return $this->entityName . ":" . $this->entityId;
}

哪个应该 return 类似于:

public function __toString()
{
    return $em->getRepository($this->entityName)->find($this->entityId);
}

我希望我已经很好地描述了我的问题。 发送

一种解决方法是为奏鸣曲使用自定义列表块。

  1. create a new twig filter 调用了 entityFilter,这个过滤器会将 sonata admin 对象的 FQCN 转换为 sonata 生成的可读路由名称。像 admin_blablabla_show:

    public function entityFilter($entityName)
    {
        $str = str_replace('\', '_', $entityName);
        $str = str_replace('Bundle', '', $str);
        $str = str_replace('_Entity', '', $str);
        $str = 'Admin' . $str . '_Show';
        return strtolower($str);
    }
    
    public function getName()
    {
        return 'my_extension';
    }
    
  2. 在你的admin class中,将所需字段的模板设置为新的twig模板:

        ->add('orderItems', null, array(
            'template' => 'AcmeBundle::order_items_list.html.twig'
        ))
    
  3. 在你的新树枝模板中(order_items_list.html.twig):

    {% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
    {% block field %}
    <div>
        {% for item in object.orderItems %}
            {% if entity(item.entityName) == 'admin_first_entity_show' %}
                {% set foo = 'Apple ID' %}
            {% elseif entity(item.entityName) == 'admin_second_entity_show' %}
                {% set foo = 'Device Accessory' %}
            {% else %}
                {% set foo = 'Not defiend' %}
            {% endif %}
    
            <a target="_blank" class="btn btn-default btn-xs" href="{{ path(entity(item.entityName), {'id': item.entityId}) }}"><i class="fa fa-external-link"></i> {{ foo }}</a>
        {% endfor %}
    </div>
    {% endblock %}