Search code examples
phpimagesymfonyvichuploaderbundleliipimaginebundle

Symfony 4 - VichUploader - How to remove image preview in edit form?


in my project symfony 4 I implemented the possibility for my users to have an avatar they could upload from their profile page, thanks to VichUploader.

To display their current avatar, I use LiipImagineBundle. Except that because of the following line in my twig:

<div class="form-row align-items-end">
            <div class="col-md-5">{{form_row(form.avatar)}}
            </div>
        </div>

I have the chamf allowing me to select an image, but I also have the preview of the avatar wholesale, and I do not want it. And I can not clear it.

Or the goal would be to be able to display it directly with LiipImagine, with code to insert in the {{form_row}} so that I would not have to bother to re-display the image next to it, like this :

{% if user.avatar.imageName %}
            <img src="{{ vich_uploader_asset(user.avatar, 'imageFile') | imagine_filter('avatar_big') }}" alt="">
        {% endif %}

Thanks for your help !


Solution

  • You can override the form field template, for all Vich image fields or just this one. To change the template for all Vich image field, include this in your form theme:

    {%- block vich_image_widget -%}
        <div class="vich-image">
            {{- form_widget(form.file) -}}
            {%- if form.delete is defined -%}
                {{- form_row(form.delete) -}}
            {%- endif -%}
            {# REMOVE THE BLOCK BELOW TO REMOVE IMAGE OR DOWNLOAD LINKS#}
            {%- if image_uri -%}          
                <a href="{{ asset_helper is same as(true) ? asset(image_uri) : image_uri }}"><img src="{{ asset_helper is same as(true) ? asset(image_uri) : image_uri }}" alt="" /></a>
            {%- endif -%}
            {%- if download_uri -%}
                <a href="{{ asset_helper is same as(true) ? asset(download_uri) : download_uri }}">{{ translation_domain is same as(false) ? download_label : download_label|trans({}, translation_domain) }}</a>
            {%- endif -%}
        </div>
    {%- endblock -%}
    

    The original file: https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/views/Form/fields.html.twig

    Check the symfony site on how to use a custom form theme: https://symfony.com/doc/4.1/form/form_customization.html