Search code examples
phpsymfonysonata-admin

Sonata Admin - How to add a link to a field


I have a field on my form in Sonata Admin:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('filePath', TextType::class, [
            'disabled' => true,
        ]);
}

protected function configureShowFields(ShowMapper $showMapper)
{
    $showMapper
        ->add('filePath');
}

This relates to an entity which stores the path of a file.

class User 
{
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $filePath;

How can I update the form so that I am able to click on the field so that it opens the file in another tab?


Solution

  • You need to declare a template inside configureShowFields for the filePath field, here is a sample for your case:

    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('filePath', null, [
                'template' => '@App/Admin/file_path_link.html.twig',
            ]);
    }
    

    And the @App/Admin/file_path_link.html.twig:

    {% if value %}
    <a href="{{ value }}">click to download</a>
    {% else %}
    No file path
    {% endif %}