Symfony2 + CreateFormBuilder how to render an image in a form
forms, image, symfony, templates
Solution
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:
- http://symfony.com/doc/current/book/forms.html#form-theming
- http://symfony.com/doc/current/cookbook/form/form_customization.html
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 %}
Problem
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) }}` ?