SonataAdmin - 如何在显示特定操作链接之前添加自定义逻辑

时间:2016-07-27 16:26:04

标签: symfony sonata-admin symfony-sonata

我知道我们可以在我们的实体管理类中自定义我们想要的操作链接,这要归功于:

$listMapper
    ->addIdentifier('name')
    ->add('minRole')
    ->add('_action', null, [
        'actions' => [
            'show' => [],
            'edit' => [],
            'delete' => []
        ]
    ])
;

或通过该服务管理角色:sonata.admin.security.handler.role

在我的情况下,我想添加一个域逻辑,以显示或不显示删除按钮(它出现在视图列表编辑视图)。

{% if attribute(object, hasEvents) is defined and not object.hasEvents %}
   # display it
{% endif %}

我不知道如何覆盖Sonata的树枝模板才能做到这一点。仅涉及两个实体:EventPost

修改

查看列表我直接覆盖了list__action_delete.html.twig模板(我创建了app/Resources/SonataAdminBundle/views/CRUD/list__action_delete.html.twig),这就是代码(我知道这不是最好的方法......) :

{#

The template override the basic one in order to prevent the display of the delete button (in the view list) for the entities
Post and Event. We only display it if they don't have associated activities.

#}
{% if admin.isGranted('DELETE', object) and admin.hasRoute('delete') %}
    {% if not attribute(object, 'isDeleteable') is defined %}
        <a href="{{ admin.generateObjectUrl('delete', object) }}" class="btn btn-sm btn-default delete_link" title="{{ 'action_delete'|trans({}, 'SonataAdminBundle') }}">
            <i class="fa fa-times"></i>
            {{ 'action_delete'|trans({}, 'SonataAdminBundle') }}
        </a>
    {% else %}
        {% if object.isDeleteable %}
            <a href="{{ admin.generateObjectUrl('delete', object) }}" class="btn btn-sm btn-default delete_link" title="{{ 'action_delete'|trans({}, 'SonataAdminBundle') }}">
                <i class="fa fa-times"></i>
                {{ 'action_delete'|trans({}, 'SonataAdminBundle') }}
            </a>
        {% endif %}
    {% endif %}
{% endif %}

1 个答案:

答案 0 :(得分:1)

我将以编辑模板为例向您展示解决方案。您应该按照相同的方法搜索要覆盖的任何其他部分/块/模板。

您要做的是覆盖/扩展编辑模板的格式块。该块在sonata管理包的 base_edit_form.html.twig 模板中定义:

vendor/sonata-project/admin-bundle/Resources/views/CRUD/base_edit_form.html.twig

要覆盖模板,有不同的方法。您可以使用symfony doc about how to override any part of a bundle中描述的方法,也可以使用config options to override the path for some of the sonata templates as described in the docs

我建议使用后者。假设您有 AppBundle ,并希望使用它来覆盖模板。将这些行添加到app/config/config.yml文件中的sonata配置部分:

sonata_admin:
    templates:
        edit: AppBundle:CRUD:edit.html.twig

创建文件src/AppBundle/Resources/views/CRUD/edit.html.twig并从中复制格式vendor/sonata-project/admin-bundle/Resources/views/CRUD/base_edit_form.html.twig模板。不要忘记扩展sonata bundle附带的 base_edit.html.twig 模板(第一行):

{% extends 'SonataAdminBundle:CRUD:base_list.html.twig' %}

{% block formactions %}
    ...
{% endblock formactions %}

格式块中找到删除按钮,并添加自定义if语句,执行您想要执行的任何操作。