How to get images listed in sonata admin bundle backend

元气小坏坏 提交于 2019-12-06 08:58:40

The simplest way is to create custom admin field template. In configureListFields method add:

->add('path', null, array('template' => 'AcmeBundle:Admin:list_image.html.twig'))

And create file AcmeBundle/Resources/views/Admin/list_image.html.twig with content:

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

{% block field%}
    <div>
        <img src="{{ object.webPath | imagine_filter('gallery_element_admin') }}" />
        {# or whatever to create src of image #}
    </div>
{% endblock %}

I needed something similar and this is my result after a while of searching the internet.

I have added tbe template in the configureListFields method from the admin class:

        ->add('culture', "string", array(
            'template' => 'AEWBackendBundle:CRUD:list_culture_image.html.twig'
        ))

I have created the template in the view:

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

{% block field%}
    <div>
        {% set flag = web_path ~ 'images/flags/' ~ object.culture.name(object) ~ '.png' %}
        {% if file_exists(flag) %}
            <img id="culture_image" title="{{ object.culture }}" src="/images/flags/{{ object.culture.name }}.png" height="15" />
        {% else %}
            <img id ="culture_image" title="en" src="/images/flags/default.png" height="15" />
        {% endif  %}
    </div>
{% endblock %}

In parameters.yml:

web_path: %kernel.root_dir%/../web/

In config.yml:

twig:
    globals:
        web_path: %web_path%

Created the TwigExtension.php file to use the file_exists PHP function as a twig extension

<?php

namespace AEW\FrontendBundle\Services\Extension;

use \Twig_Filter_Function;
use \Twig_Filter_Method;

class TwigExtension extends \Twig_Extension
{

    /**
     * Return the functions registered as twig extensions
     * 
     * @return array
     */
    public function getFunctions()
    {
        return array(
            'file_exists' => new \Twig_Function_Function('file_exists'),
        );
    }

    public function getName()
    {
        return 'twig_extension';
    }
}

Added the config lines in config.yml for the new extension:

parameters:
    aew.twig_extension.class: AEW\FrontendBundle\Services\Extension\TwigExtension

services:
    aew.twig_extension:
        class: %aew.twig_extension.class%
        tags:
            - { name: twig.extension }

Hope this helps you or anyone else who is looking for this info in the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!