Skip to content

Instantly share code, notes, and snippets.

@Padam87
Created October 17, 2016 18:58
Show Gist options
  • Save Padam87/835a7025635d5ebc712421a50eec89d7 to your computer and use it in GitHub Desktop.
Save Padam87/835a7025635d5ebc712421a50eec89d7 to your computer and use it in GitHub Desktop.
Sonata list route type
{% extends admin.getTemplate('base_list_field') %}
{% block field %}
{% set parameters = {} %}
{% for name, value in field_description.options.parameters %}
{% set parameters = parameters|merge({ (name): call_user_func(value, object) }) %}
{% endfor %}
<a {% for name, value in field_description.options.a.attributes %}{{ name }}="{{ value }}" {% endfor %}
href="{{ path(call_user_func(field_description.options.name, object), parameters) }}" >
{{ call_user_func(field_description.options.a.html, object)|raw }}
</a>
{% endblock %}
<?php
class PhpFunctionExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction('call_user_func', 'call_user_func'),
new \Twig_SimpleFunction('call_user_func_array', 'call_user_func_array'),
];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'phpfunc';
}
}
@Padam87
Copy link
Author

Padam87 commented Oct 17, 2016

You can use this instead of the extension: https://github.com/umpirsky/twig-php-function

Usage

$listMapper
    ->add(
        'url',
        'route',
        [
            'name' => function (Content $content) {
                return 'route_name';
            },
            'parameters' => [
                'id' => function (Content $content) {
                    return $content->getId();
                },
                'slug' => function (Content $content) {
                    return $content->getSlug();
                }
            ],
            'a' => [
                'html' => function (Content $content) {
                    return $content->getTitle();
                },
                'attributes' => [
                    'target' => '_blank'
                ]
            ]
        ]
    )
;

@mfrieling
Copy link

Using Symfony 4.3, how can I tell Sonata to use the custom template? I only get an error that the (original) template doesn't understand this syntax ("Catchable Fatal Error: Object of class Closure could not be converted to string") and the list_url template is not listed here as overridable: https://symfony.com/doc/master/bundles/SonataAdminBundle/reference/templates.html#configuring-templates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment