The Maniac
The Maniac

Reputation: 2626

Symfony 2: "File" field value is always empty

I'm attempting to make a form that builds a slider. It can have any number of images and I'd like to show a preview of already-uploaded images. Getting the multiple image field set up was easy enough, but I'm getting caught up on showing a preview of the image.

I'm using this template to render the "Slider Image" field:

{% block form_widget_simple %}
{% spaceless %}
    <div class="form-widget slider">
        {% set type = type|default('text') %}
        {% if type == 'file' and value is not empty %}
            <img src="{{ value }}" width="200"/><br/>
        {% endif %}
        <input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
    </div>
{% endspaceless %}
{% endblock form_widget_simple %}

The value variable is always empty on file input types, so I'm not sure how I can get at the url of the uploaded images. I am using a custom field type that simply adds a file field and hooks up the data source (which is just a simple wrapper around Symfony\Component\HttpFoundation\File\File). If you need this code let me know, but its all boilerplate stuff so I doubt you do.

Thanks in advance.

Upvotes: 4

Views: 4238

Answers (1)

Norbert Orzechowicz
Norbert Orzechowicz

Reputation: 1311

Symfony2 FileType doesn't have value, its owerwritten in buildView method. https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/Type/FileType.php#L28

But you access it via forms.vars.data

    {% if type == 'file' and form.vars.data is not null %}
        {# Here you should somehow generate url to file but let assume 
           you have it in "/path/to/file/" folder that is accessible through web server #}
        <img src="/path/to/file/{{ form.vars.data.name }}" /><br/>
    {% endif %}

Upvotes: 7

Related Questions