Symfony 2: "File" field value is always empty - symfony

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.

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 %}

Related

Reuseable blocks inside of custom form themes in symfony

I want to call a custom block inside an overwritten theme-block:
{% block file_widget %}
{% if image is not null %}
{{ block('imagePreview') }}
{% endif %}
{{ block('form_widget') }}
{% endblock %}
{% block imagePreview %}
<img src="{{ image.getFullPath | imagine_filter('medium_square') }}"
alt="{{ image.filename }}"/>
{% endblock %}
The imagePreview is not shown.
But it is working when I don't use a block.
And it is also working when I dont use a FormTypeExtension and create an ImageType instead.
So I guess the file_widgetblock still has the scope of the parent form_div_layout.html.twig and there in fact no imagePreview block exists.
So how can I solve this.
I mean now I solved it by removing the block.
But I just want to know if someone has a solution to this.
Maybe there is a way for using reuseable blocks inside of custom form themes in symfony?
Finally I found the solution:
I just did not 'use' the base template explicit.
The form theme worked without this - because symfony falls back the the base form theme when it does not find a block inside the new theme file.
But it seems then you also can not use custom blocks inside this new theme file.
So this works now:
{% use 'form_div_layout.html.twig' %}
{% block file_widget %}
{% if image is not null %}
{{ block('imagePreview') }}
{% endif %}
{{ block('form_widget') }}
{% endblock %}
{% block imagePreview %}
<img src="{{ image.getFullPath | imagine_filter('medium_square') }}"
alt="{{ image.filename }}"/>
{% endblock %}

Twig Runtime Error: Impossible to invoke a method ("test") on a string variable

I have the following twig template (the code is in the same file):
{% macro renderJob(fields) %}
// renders the job UI block, but I've removed it for simplicity
Hello world.
{% endmacro %}
{% block _jobs_widget %}
<div id="jobsContainer">
{% for fields in form.children %}
{% dump fields %}
{{ _self.renderJob(fields) }}
{% endfor %}
</div>
{% endblock %}
For some reason, after upgrading to twig/twig = v2.1.0 I'm receiving the follwing error:
Impossible to invoke a method ("renderJob") on a string variable ("#AppBundle/Jobs/form/job.html.twig").
I have been trying to figure out what's causing this without any luck. This used to work just fine in 1.3.x. The fields variable contains the proper data, but it appears it can't pass it to the renderJob macro or it can't find the macro (which is kind of odd)?
Have you tried the following ?
{% import _self as renderJobMacro %}
{% macro renderJob(fields) %}
// renders the job UI block, but I've removed it for simplicity
Hello world.
{% endmacro %}
{% block _jobs_widget %}
<div id="jobsContainer">
{% for fields in form.children %}
{{ renderJobMacro.renderJob(fields) }}
{% endfor %}
</div>
{% endblock %}
I think _self is depricated from twigg 2.0, May be you need to check without _self.
Check {{ renderJob(fields) }} instead of {{ _self.renderJob(fields) }}

eZ Publish 5: get absolute url of an image attribute of a class

In eZ Publish 5, I have a class with an image attribute.
Within the twig template, I can get the relative url (e.g. '/var/site/storage/image/...') from the attribute parameters.
Now I need the absolute url. Which is the best way to get it?
Should I get the request information and append the base url to the relative one? Or there's a built in method for that?
Thanks
You should do something like this:
{{ asset( ez_image_alias( content.getField( 'image' ), content.versionInfo, 'original' ).uri, absolute=true ) }}
ez_image_alias is used to get the image alias (obviously), and here we get the original variation.
Then we take the uri of the image alias, and pass it to symfony asset function.
That should work.
Yes this the correct answer.
Just don't forget to add some tests before such as :
Check if the content field you want to retrieve data from exists and if that field is not empty :
{% if content.fields['myFieldIdentifier'] is defined and not ez_is_field_empty(content, 'myFieldIdentifier') %}
{# do the job #}
{% endif %}
Here's how the ImageFieldType is rendered by default :
{% block ezimage_field %}
{% spaceless %}
{% if not ez_is_field_empty( content, field ) %}
<figure {{ block( 'field_attributes' ) }}>
{% set imageAlias = ez_image_alias( field, versionInfo, parameters.alias|default( 'original' ) ) %}
<img src="{% if imageAlias %}{{ asset( imageAlias.uri ) }}{% else %}//:0{% endif %}"{% if imageAlias.width is defined %} width="{{ imageAlias.width }}"{% endif %}{% if imageAlias.height is defined %} height="{{ imageAlias.height }}"{% endif %} alt="{{ field.value.alternativeText }}" />
</figure>
{% endif %}
{% endspaceless %}
{% endblock %}

Symfony Twig customize an Individual field for a collection

In the documentation there is a way in Symfony to customize a Individual field, based on the name/id of the widget.
{% form_theme form _self %}
{% block _product_name_widget %}
<div class="text_widget">
{{ block('field_widget') }}
</div>
{% endblock %}
{{ form_widget(form.name) }}
Here, the _product_name_widget fragment defines the template to use for the field whose id is product_name (and name is product[name]).
This works for a normal widget, but not if a widget is inside a collection. Because of the extra columns. Like this:
name="productbundle_product_type[foobar][1][value]" id="productbundle_product_type_foobar_1_value"
What is the way to make the Twig customization work inside the collection?
I thought something like this, but that doesn't work:
{% for db in edit_form.list %}
{% block _productbundle_product_type_foobar_{{ db.name }}_widget %}
<div class="text_widget">
{{ block('field_widget') }}
</div>
{% endblock %}
{% endfor %}
Even the following doesn't work:
{% _productbundle_product_type_foobar_1_value_widget %}
What is the way to make it work?
I was working on a project a couple of evenings ago and encountered precisely this problem - the solution I found is a pair of blocks that look like this (stripped of project-specific code):
{# Collection markup #}
{% block my_collection_widget %}
{# Customise collection row prototype for allow_add #}
{% if prototype is defined %}
{% set data_prototype = block('my_collection_item_widget') %}
<div id="my_prototype" data-prototype="{{ data_prototype }}" style="display: none"></div>
{% endif %}
{% for prototype in form %}
{{ block('my_collection_item_widget') }}
{% endfor %}
{% endblock my_collection_widget %}
{# Collection row markup #}
{% block my_collection_item_widget %}
{# Collection contains simple, single type #}
{{ form_errors(prototype) }}
{{ form_label(prototype) }}
{{ form_widget(prototype) }}
{# OR #}
{# Collection contains a compound type, render child types independantly #}
{{ form_errors(prototype.inner_widget) }}
{{ form_label(prototype.inner_widget) }}
{{ form_widget(prototype.inner_widget) }}
{% endblock my_collection_item_widget %}
I know this is old question, but maybe people still happening upon this. This is explained fragment naming for collections.
You use _entry_ in these cases in place of the collection element number. Use the instructions in the link for fragment naming, but this might vary. Sometimes 'type' is part of the fragment's name, sometimes first letter is upper case, sometimes lower case, etc. I would use a browser developer tool to find the actual name to make sure. You might also be able to customize the names used by adding the getBlockPrefix function to the form class.
Therefore, in your case above, the customized block might look something like:
{% block _ProductBundle_product_entry_widget %}
<div> {{ form_row(form.field)}} </div>
{% endblock %}
Where 'field' would be the name of a field in the element of your collection.
A few things here:
1. Documentation Error
The docs seem to be a bit off with CamelCase entities. As for 5.3 it should be: _taskManager_taskLists_entry_widget (instead of _task_manager_task_lists_entry_widget)
You can confirm the naming by dumping the form or form field: {{ dump(form) }} or {{ dump(form.yourField) }} in your template and then look for unique_block_prefix within the vars section.
2. Do NOT use the block overrides, macros are much more easy
It makes things absolutely more complicated than necessary. Simply define a macro:
{% import _self as formMacros %}
{% macro formatCollection(form) %}
<div class="form-group row">
<div>
{{ form_widget(form.field1) }}
{{ form_widget(form.field2) }}
{{ form_widget(form.field3) }}
</div>
</div>
{% endmacro %}
then simply run it on each collection:
{% for item in form.collectionItems %}
{{ formMacros.formatCollection(item) }}
{% endfor %}
3. Prototype
Get the prototype before rendering the collection field. You can store it in a variable.
{% set prototype = form.collection.vars.prototype %}
Then simply render it whenever you like using our macro:
<div data-js="collection" data-prototype="{{ formMacros.formatCollection(prototype)|e('html_attr') }}">

Maximum function nesting when extending twig template for sonata admin

I am using the following template to extend specific widget
{% use 'SonataAdminBundle:Form:form_admin_fields.html.twig' %}
{% form_theme form _self %}
{% block textarea_widget %}
{% spaceless %}
<div class="textarea_widget">
<textarea {{ block('widget_attributes') }}>{{ value|raw }}
</textarea>
</div>
{% endspaceless %}
{% endblock textarea_widget %}
The main problem is that it's reaching maximum function nesting. There must be some infinite recursion when extending template. When i copied code from extended template everything works. Any idea how to make this working?
This is probably caused by xDebug that you must configure with xdebug.max_nesting_level parameter. Default is 100 but I usually upgrade it to 1000 to be quiet.
On a Debian, it's in /etc/php5/conf.d/xdebug.ini.
Official doc about this parameter:
xdebug.max_nesting_level Type: integer, Default value: 100
Controls the protection mechanism for infinite recursion protection.
The value of this setting is the maximum level of nested functions
that are allowed before the script will be aborted.
to fix this error i needed to create form_admin_fields.html.twig file in app/Resources/SonataAdmin/views/Form with the following content:
{% block textarea_widget %}
{% spaceless %}
<div class="textarea_widget">
<textarea {{ block('widget_attributes') }}>{{ value|raw }} </textarea>
</div>
{% endspaceless %}
{% endblock %}
So there is no necessity to use or extend template just redefine some block.

Resources