Twig loop and building hash - symfony

i have a problem with twig syntax and merge function ... I have multiple object with 2 field category and price.
I need to create an array or hash (i guess hash is easier but ... i try both) with sum of prices for each category.
So i try many code, and my last is :
{% set test = [ {'category': 'description', 'price': '1'}, { 'category': 'abc', 'price': '2'}, { 'category':'description', 'price': '3'} ] %}
{% set listCategory={} %}
{% for line in test %}
{% set new_category = { 'category': line.category, 'price': line.price } %}
{% if loop.first %}
{% set listCategory = listCategory|merge([new_category]) %}
{% else %}
{% set flag = false %}
{% for category in listCategory %}
{% if line['category'] == new_category['category'] %}
{% set tmp = line['price'] + new_category['price'] %}
{# i try it too#}
{% set category = category|merge([tmp]) %}
{# or i try this#}
{% set category = category|merge({ (category.price) : category.price + new_category.price }) %}
{{ dump(listCategory) }}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
I try it since 3 hours and i don't know where i make an error.
When i check my array, i test if the key 'name' exist
if yes, i want to add the price of element to the hash price
if no, i want to add a new array in hash with key = 'name'
Anyone have an idea ? thx for your reading.

I think you are looking for something similar to:
{% set test = [ {'category': 'description', 'price': 1}, { 'category': 'abc', 'price': 2}, { 'category':'description', 'price': 3} ] %}
{% set listCategory={} %}
{% for line in test %}
{% set key = line.category %}
{% if listCategory[key] is defined %}
{# notice here that the key is in brackets () because otherwise it will be interpreted as the string "key" %}
{% set listCategory = listCategory|merge({(key):listCategory[line.category]+line.price}) %}
{% else %}
{% set listCategory = listCategory|merge({(key):line.price}) %}
{% endif %}
{{ key }}: {{ listCategory[key] }}
{% endfor %}

Related

Is there a way to define logic in a block rather than in a bunch of individual tags?

For Example I have quite a lot of logic that looks like this
{% set allowed_observations = ["PAR;101;ZN_GYM", "PAR;101;ZN_CARDIOGYM", "PAR;101;0;G15"] %}
{% set allowed_observations_names = ["Downstairs Gym", "Upstairs Gym (Cardio)", "Swimming Pool"] %}
{% for observation in observations %}
{% if (observation.location.locationCode in allowed_observations) %}
{% if ("HeadCount" in observation.observationTag) %}
{% set name = "" %}
{% for key,value in allowed_observations %}
{% if (value == observation.location.locationCode) %}
{% set name = allowed_observations_names[key] %}
{% endif %}
{% endfor %}
{% set data = data | push({
name: name,
location: observation.location.locationCode,
value: observation.value
}) %}
{% endif %}
{% endif %}
{% endfor %}
I was wondering if you can just do a single {% ...all code... %} type thing, using ; for line breaks or something?

Translate dynamic variable in twig

How do I translate this in twig? I have this variable in twig that is an array:
$array = [
['number' => 7, 'name' => 'foo'],
['number' => 8, 'name' => 'bar'],
['number' => 10, 'name' => 'baz'],
// ... and so on and so forth
]
Would like it to be something like this:
The variables are 7 times for foo, 8 times for bar, and 10 times for baz.
Or
The variables are 7 times for foo and 10 times for baz.
Or
The variable is 7 times for foo.
Tried with something like this:
{% set last = array|last %}
{% set array = array|slice(0, array.length - 1) %}
{% trans %}
<p>The variables are
{% for i in array %}
{{ i.number }} times {{ i.name }},
{% endfor %}
, and {{ last.number }} number of {{ last.name }}
.</p>
{% endtrans %}
Thanks!
Try this
The variables are
{% for item in array %}
{% if array|length > 1 and loop.last %}
and
{% endif %}
{{ item.number }} times for {{ item.name }}{% if loop.last %}.{% elseif array|length > 2 %}, {% endif %}
{% endfor %}

Twig compare two values in different arrays

First of all I'm learning Twig.
I was wondering if it is possible wit Twig to compare two different values from different arrays/lists?!
I have two list of items I call them like so:
{% if page.cart %}
{% for product in page.cart.products %}
{{ product.id }}
{% endfor %}
{% endif %}
And:
{% if products %}
{% for product in products %}
{{ product.id }}
{% endfor %}
{% endif %}
I want to compare both product.id's so I can create a new statement. Is there any way to compare both values? The idea is to check if an id is present in page.cart.products and if so then do something.
I want to create a new statement to display some info. Something like so:
{% if page.cart %}
{% for product in page.cart.products %}
{% set cartId %}{{ product.id }}{% endset %}
{% endfor %}
{% endif %}
{% if products %}
{% for product in products %}
{% set listId %}{{ product.id }}{% endset %}
{% endfor %}
{% endif %}
{% if cartId == listId %}
.... do this ....
{% endif %}
Any help greatly appreciated!
You can loop over one array and check if the id is present in the second one. If it's there, you can do something.
{# In case you want to store them, you can do so in an array #}
{% set repeatedIds = [] %}
{% for productCart in page.cart.products if page.cart %}
{% for product in products if products %}
{% if productCart.id == product.id %}
<p>This id -> {{ product.id }} is already in page.cart.products</p>
{% set repeatedIds = repeatedIds|merge([product.id]) %}
{% endif %}
{% endfor %}
{% endfor %}
{{ dump(repeatedIds) }}
It's a very basic search algorithm and the cost is quadratic. Obviously, there are more efficient ways to look for an element in an array (though more complicated to implement).
If the amount of products you have to deal with is not very big, you could use this solution. However, if you have, let's say, more than one hundred products in each array (or you feel that the algorithm is slowing down your loading time), you could do this process in the controller using more sophisticated methods and PHP and just pass the result to the template.
Hope it helps.

Twig - Why can't I access a variable I've set?

For some reason, a variable I'm setting in one form template bloc is not available in a child form block.
I have an 'entity' field type to present a selection of checkboxes to allow the user to select related items...
$builder
->add( 'title' )
->add(
'apps',
'entity',
[
'class' => 'OurAdminBundle:App',
'choices' => $apps,
'property' => 'title',
'expanded' => true,
'multiple' => true
]
)
And here's the template that renders the form
// Effectively imported using the MopaBootstrapBundle
// {% form_theme form 'OurAdminBundle:Form:fields.html.twig %}
// Further in page theming
{% form_theme form _self %}
// Set variable when on the apps field, so it should be available to all child
// forms
{% block _gallery_apps_widget %}
{% set custom_checkboxes = 1 %}
{{ block('choice_widget') }}
{% endblock %}
// Attempt to retrieve the variable on the checkboxes within the apps entity
/ field
{% block checkbox_widget %}
{{ dump(custom_checkboxes|default(0) }} // Displays 0
{% endblock checkbox_widget %}
Here's the code from the fields.html.twig file (with minor debugging additions...
{% block choice_widget_expanded %}
{{ dump(custom_checkboxes|default(0)) }}
{% set custom_checkboxes = custom_checkboxes|default(0) %}
{{ dump(custom_checkboxes|default(0)) }}
{% spaceless %}
{% set label_attr = label_attr|merge({'class': (label_attr.class|default(''))}) %}
{% set label_attr = label_attr|merge({'class': (label_attr.class ~ ' ' ~ (widget_type != '' ? (multiple ? 'checkbox' : 'radio') ~ '-' ~ widget_type : ''))}) %}
{% if expanded %}
{% set attr = attr|merge({'class': attr.class|default(horizontal_input_wrapper_class)}) %}
{% endif %}
{% for child in form %}
{% if widget_type != 'inline' %}
<div class="{{ multiple ? 'checkbox' : 'radio' }}">
{% endif %}
<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>
{{ form_widget(child, {'horizontal_label_class': horizontal_label_class, 'horizontal_input_wrapper_class': horizontal_input_wrapper_class, 'attr': {'class': attr.widget_class|default('')}}) }}
{{ child.vars.label|trans({}, translation_domain) }}
</label>
{% if widget_type != 'inline' %}
</div>
{% endif %}
{% endfor %}
{% endspaceless %}
{% endblock choice_widget_expanded %}
... which successfully displays '1' on both counts.
I've racked my brains over this one, but can't for the life of me understand why I can't access the variable in the checkbox_widget block. Please help.
This is due to how Symfony renders form fields when calling form_widget() or any other form* family of functions.
Symfony creates a new separate scope which do not share the scope of the parent (in order to prevent scope polluting while rendering fields).
If you which to pass a variable to the checkbox widget, edit the form_widget call in the choice_widget_expanded to pass on the custom_checkboxes as so (added tabbing for clarity only):
{{ form_widget(child, {
'horizontal_label_class': horizontal_label_class,
'horizontal_input_wrapper_class': horizontal_input_wrapper_class,
'attr': {'class': attr.widget_class|default('')},
'custom_checkboxes': custom_checkboxes
}) }}

Set variable in loop

I'm trying to create a json object on twig, so I need to set a variable inside a loop.
After many attempts I found this way, but it's fine when I only have two records, if I have any more you generate the problem:
{% set data = [] %}
{% for artist in artists %}
{% if loop.first %}
{%
set data = {
id : artist.id,
text : artist.name|capitalize() ~' '~ artist.surname|capitalize()
}
%}
{% else %}
{%
set data = [data,{
id : artist.id,
text : artist.name|capitalize() ~' '~ artist.surname|capitalize()
}]
%}
{% endif %}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}
What I want to achieve is:
{results: [{id: 1, text: "bla"},{id: 2, text: "blabla"},{id: 3, text: "blablabla"}]}
Instead I get:
{results:[[{id:1,text:"bla"},{id:2,text:"blabla"}],{id:3,text:"blablabla"}]}
Is there a way to build a json object inside twig without going crazy?
I've already tried this way .. but rewrites the object and saves in the variable only the last element:
{% set data = [] %}
{% for artist in artists %}
{%
set data = {
id : artist.id,
text : artist.name|capitalize() ~' '~ artist.surname|capitalize()
}
%}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}
Use merge.
{% set data = [] %}
{% for artist in artists %}
{%
set data = data|merge ([{
id : artist.id,
text : artist.name|capitalize() ~' '~ artist.surname|capitalize()
}])
%}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}

Resources