Symfony2 + CreateFormBuilder how to make an image in the form

I am creating a Symfony2 form and CreateFormBuilder to create my form.

I am currently using {{ form_widget(form) }} to display a form. My entity has a path property, which is a way to save the image in the file system. I want to display an image in a form (with an <img> html tag), how can I achieve this result? Should I process the form in the field of my template by field? Or is there a way to own only one field in a template and display others using {{ form_widget(form) }} ?

+4
source share
1 answer

What you can do is process the form field by field and display the image if the value is set.

Say you have an image field name. In Twig, you can access its value through form.vars.value.image . Then it's pretty easy to display the img tag:

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

Here upload/dir/ is the 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 would be to create your own type with your own template:

Edit: I forgot an interesting alternative. You can set up 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 %} 
+7
source

All Articles