Twig - display a property inside an entity item - symfony

I have an entity that has an items property that is an array of item entities. the item entity has id and name properties.
what I want to do is to get entity.items and display all name properties, separated by commas.
the way I have it now:
<tr>
<th>Items</th>
<td>
{% for item in entity.items %}
{{ item.name }}
{% endfor %}
</td>
</tr>
But it is not separated by commas. I tried the Join filter, but I can't find a way to use it in this situation, since I have an array of objects.

You can combine twig syntax with regular HTML. The {%%} markup indicates tags, telling the twig that there's some rendering logic, but you don't need to write strictly twig syntax inside the tags. So:
{% for item in entity.items %}
{{ item.name }}{% if not loop.last %}, {% endif %}
{% endfor %}
will work just fine

Related

Iterate lists/content in block template twig Drupal 8

How would I be able to supersede the hierarchical dependencies in Drupal 8's twig engine to be able to loop within the i.e Lists/Views which is assigned to a block. So we would have a template: block--views-block--[machine-name]-1.html.twig You will be required to have the variable {{ content }}
Which then recursively buries itself down to field templates. Its completely killing me that one would need so many levels to produce on block of content.
I would like to iterate within the top custom block template the list.
Attempted
{% for key, value in _context %}
<li>{{ key }}</li>
{% endfor %}
To evaluate what is available to iterate down into the object but with no luck. I did though find a nice overriding object structure to reach the field attributes but that was within the field level
item.content['#item'].entity.uri.value
Thanks
i use this to "generate" a picture from my
node--news--full.html.twig
<div class="col-md-3">
{{ content.field_newsbild }}
</div>
the twig debug suggests some filenames. i took this:
field--node--field-newsbild--news.html.twig
and in there i wrote:
{% for item in items %}
<img alt="" src="{{ file_url(item.content['#item'].entity.uri.value) }}" class="img-responsive" {{ attributes }} >
{% endfor %}
hope i'll help a bit.

How to get Pagination direction in twig for KNP paginator?

I am using knp paginator and it works well but when I want to use its sorting feature I have problem to get the sort direction in twig.
the following code is indicate how to get the sorted table header but not taking about how to get sorted table header direction.
{# total items count #}
<div class="count">
{{ pagination.getTotalItemCount }}
</div>
<table>
<tr>
{# sorting of properties based on query components #}
<th>{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}</th>
<th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'Title', 'a.title') }}</th>
</tr>
{# table body #}
{% for article in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ article.id }}</td>
<td>{{ article.title }}</td>
</tr>
{% endfor %}
</table>
{# display navigation #}
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
I get this code from KnpPaginator documentation on following link:
https://github.com/KnpLabs/KnpPaginatorBundle
You should be able to just use {{ pagination.getDirection() }} in your twig template to find the current sort direction (if any) then set up your classes based on that.
{% set direction = pagination.getDirection() %}
<th{% if pagination.isSorted('p.id') %} class="sorted {{ direction }}"{% endif %}>
{{ knp_pagination_sortable(pagination, 'Id', 'p.id') }}
</th>
But... as of this post, KNP has not yet merged this fix:
https://github.com/sroze/KnpPaginatorBundle/commit/3105a38714c6f89c590e49e9c50475f7a777009d
When there is no direction parameter set, the current Paginator bundle throws an error.
So, until the above fix is merged, you can still get the direction with a bit more verbosity:
{% set directionParam = pagination.getPaginatorOption('sortDirectionParameterName') %}
{% set params = pagination.getParams() %}
{% set direction = params[directionParam] is defined ? params[directionParam] : null %}
<th{% if pagination.isSorted('p.id') %} class="sorted {{ direction }}"{% endif %}>
{{ knp_pagination_sortable(pagination, 'Id', 'p.id') }}
</th>
When you call {{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}, bundle automatically generates link with a class holding an information about sort direction, which looks something like this: <a translationcount="" class="asc" href="?sort=a.id&direction=desc&page=1" title="Id">Id</a> So just put this class in your css file and style it with the arrow. If you, for some reason, need to get a sort direction inside a controller, just read it from request $request->query->get('direction').

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') }}">

How are labels on ArrayCollections in forms rendered?

I have a Customer object, which has many Emails.
I'm building a form for my customer, and I've added his emails as a collection. In my template, I render the emails portion like this:
<h4>Emails</h4>
{% for email in form.emails %}
<li>
{{ form_row(email.addr) }}
{{ form_row(email.isPrimary) }}
</li>
{% endfor %}
...
{{ form_rest(form) }}
This works fine, except if the customer has no emails. Then, form_rest() renders the label 'emails' at the bottom of my template.
Why does this only get rendered when form.emails is empty? How can I customize it? (Note I've already customized my label rendering for other form elements, and I don't want it to be the same for these 'collection labels'.)
I usually solved this problem this way:
{% for email in form.emails %}
{# ... #}
{% else %}
{{ form_widget(form.emails) }}
{% endfor %}
Unless someone suggests a better way of doing this.

form_rest command showing previously-rendered Collection field

I have a form with a collection type field, rendered like that:
<div id="beneficiosTab" class="opcional">
Beneficios
<ul class="beneficios" data-prototype="{{ form_widget(formAtendimento.beneficios.get('prototype')) | e }}">
{% for beneficio in formAtendimento.beneficios %}
<li>{{ form_row(beneficio.coTipoBeneficio) }}</li>
<li>{{ form_row(beneficio.vrValor) }}</li>
<li>{{ form_row(beneficio.boConcedido) }}</li>
{% endfor %}
<li>Add Beneficio</li>
</ul>
</div>
<div style="clear:both"></div>
{{ form_rest(formAtendimento) }}
The form's entity can have multiple items of the collection, or none.
When the entity has items of the collection, it works fine, but when it has none, the "for" in the twig doesn't happen, and a "Beneficios" div is generated in form_rest.
Any way I can prevent that? Thanks in advance.
This seems like a bug in the form rendering. I managed to disable the extra form rendering in the form_rest function, by adding this code just after rendering the collection elements:
{% do form.uploads.setRendered() %}
Where "uploads" is my collection field type.
This doesn't seem like best practice to me though.
So the whole rendering looks like this:
<div id="uploads" data-prototype="{{ form_widget(form.uploads.vars.prototype)|e }}">
{% for upload in form.uploads %}
{{ form_widget(upload) }}
{% endfor %}
</div>
{% do form.uploads.setRendered() %}
form_rest generate all unrendered forms. Every input is form in Symnfony2, the same goes with collection type.
You never printed out collection, so Symfony makes it for you.
If you want hide it, and still use form_rest simply print it it to:
<div style="display: none" />

Resources