Bagbyte
Bagbyte

Reputation: 863

Symfony2 + CreateFormBuilder how to render an image in a form

I'm Symfony2 and CreateFormBuilder to create my form.

Currently I'm using {{ form_widget(form) }} to display the form. My entity have path property that is the path of an image save on filesystem. I want to display the image in the form (with a <img> html tag), how can I achieve this result? Should I handle the form in my template field by field? Or is there a way to own only one field in the template and render the other ones with {{ form_widget(form) }} ?

Upvotes: 4

Views: 6901

Answers (1)

William Durand
William Durand

Reputation: 5519

What you could do is handling the form field by field, and display the image if the value is set.

Let's say you have a field name image. In Twig, you can access its value through form.vars.value.image. Then, it's quite easy to display an img tag:

{% if form.vars.value.image is not null %}
    <img src="{{ asset('upload/dir/' ~ form.vars.value.image) }}" />
{% endif %}

Here, upload/dir/ is a path where you store your images. If you have a constant for this path, you can use it in Twig:

{{ asset(constant('Acme\\DemoBundle\\Model\\Object::UPLOAD_DIR') ~ '/' ~ form.vars.value.image) }}

An alternative could be to create your own type with its own template:

Edit: I forgot an interesting alternative. You can customize an individual field: http://symfony.com/doc/current/cookbook/form/form_customization.html#how-to-customize-an-individual-field. Here is a draft of what you could do:

{% form_theme form _self %}

{% block _object_image_row %}
    <div class="name_row">
        {{ form_label(form) }}
        {{ form_errors(form) }}
        {{ form_widget(form) }}

        {% if form.vars.value.image is not null %}
            <img src="{{ asset('upload/dir/' ~ form.vars.value.image) }}" />
        {% endif %}
    </div>
{% endblock %}

Upvotes: 7

Related Questions