How can i access the ['question'] inside a loop? - twig

Array ( [status] => 1
[data] => Array (
[61d2f1fef27db255838d2c59] => Array (
[name] => General
[questions] => Array (
[0] => Array (
[id] => 61d54149c98b65a672acf79b
[question] => What will happen to posts that I made on my classic Page?
[answer] => All of your previous posts will be preserved on your Page, and insights will still be available for them.
)
[1] => Array (
[id] => 61d2eb5db97dcc3c488f0ef9
[question] => How can I add my Google Analytics id in for the mobile website ?
[answer] => Before starting, Please keep your Google Analytics id ready with you. Go to the Settings > Manage Design > Data Settings and enter your id in the analytics id field & save. Please refer to the video for step by step help.
)
)
)
[61d53eb4c98b65a672acf798] => Array (
[name] => Other
[questions] => Array (
[0] => Array (
[id] => 61d54131c98b65a672acf79a
[question] => How can I open my new Page?
[answer] => To open your new Page on desktop: From your home page, click on your profile picture in the top right. Select Switch Profile and select the new Page.
)
[1] => Array (
[id] => 61d53fc9c98b65a672acf799
[question] => What is your return policy?
[answer] => We allow returns of all items within 30 days of your order date. Just send us an email with your order number and we will send you a return label.
)
)
)
)
)
I am new to twig and i have got this data and want to access the every [question] and [answer] data. Please someone help me in order to extract question and answer using twig looping statements.
{% for data in api_response %}
{% for keys in data %}
{{ keys }}
{% endfor %}
{% endfor %}
I tried it doing this way but i am not getting any output

At this moment you are only using one loop, but as we can see, the questions are stored in another array. Meaning you'll have to loop that array as well
{% for row in result.data %}
<h2>{{ row.name }}</h2>
{% for data in row.questions %}
<p>{{ data.question }}</p>
{% endfor %}
{% endfor %}
demo
Edit from comment:
{% for row in result.data %}
{% if row.name|lower = 'general' %}
<h2>{{ row.name }}</h2>
{% for data in row.questions %}
<p>{{ data.question }}</p>
{% endfor %}
{% endif %}
{% endfor %}

Related

How to add entity extension in Shopware 6 App?

I want to query the categories of the product in the product listing of a Shopware app, so that I can query the customFields of all categories. Is this even possible with an app?
I have already tried via a navigation-page-loaded. And when I override the box-standard.html.twig and access the product, I can't access the categories there.
For each product i want the categories extensions
As the categories association is not loaded for products in the listing you have to fetch the categories using an app script.
As already noted, add the script to the navigation-page-loaded hook, i.e. in Resources/scripts/navigation-page-loaded/category-loader.twig:
{% set products = [] %}
{% if hook.page.cmsPage.type === 'product_list' %}
{% foreach hook.page.cmsPage.sections as section %}
{% foreach section.blocks as sectionBlock %}
{% if sectionBlock.type !== 'product-listing' %}
{% continue %}
{% endif %}
{% foreach sectionBlock.slots as slot %}
{% if slot.type !== 'product-listing' %}
{% continue %}
{% endif %}
{% foreach slot.data.listing.entities as product %}
{% set products = products|merge([product]) %}
{% endforeach %}
{% endforeach %}
{% endforeach %}
{% endforeach %}
{% endif %}
{% set categoryIds = products|reduce((carry, v) => carry|merge(v.categoryIds), []) %}
{% if categoryIds %}
{% set categories = services.repository.search('category', {'ids': categoryIds}) %}
{% foreach products as product %}
{% do product.addArrayExtension('myCategories', {
'categories': categories.entities.getList(product.categoryIds),
}) %}
{% endforeach %}
{% endif %}
Where we first extract all the products, than load the categories of all products at once, and than assign the categories back to the products.
Note that for reading the category entity you need the correct permission, i.e. in the manifest.xml add:
<permissions>
<read>category</read>
<read>category_translation</read>
</permissions>
Now you should be able to access in the box-standard.html.twig template the categories using product.extensions.myCategories.categories.
If I understand your issue correctly, you are trying to access a product's category's custom fields in some piece of storefront logic (like a Twig template).
The way I see it, you would have to add a script that would enable you to query the repository for the categories and their custom fields. The issue is, a SalesChannelProductEntity will not contain the information about all its categories (only the SeoCategory), so you might need to first query the product_category repository.
Generally, it is going to be complicated but it should be doable.

Twig check elements of array are in another array

I'm trying to check in twig if any element of one array are set in other array.
Example:
I have user.roles with ['ROLE_ADMIN','ROLE_MANAGER'] and I have the product.roles with ['ROLE_ADMIN','ROLE_USER'].
I want to check (in Twig) if any user.roles are in product.roles, like:
{{ user.roles[0] is product.roles|keys }}
But with each element of user.roles in the same function.
Does anyone know how?
You could use the filter filter to do this, but guessing it would be better to move this to PHP / TwigExtension
{% if user.roles |filter((role) => role in product.roles) | length > 0 %}
Can do something with the post
{% else %}
Access denied
{% endif %}
demo
Use a for loop:
{% for role in user.roles %}
{% if role in product.roles|keys %}
do something...
{% endif %}
{% endfor %}

twig variable won't pass - symfony sonata

5 days have gone by, still no success!
I dumped the results of my card variable and it returns results.
But when I try to pass it trough varibale on my twig tamplate it throws:
Variable "card" does not exist.
It's defined in SonataAdmin.
protected function configureShowFields(ShowMapper $showMapper)
{
$card = $this->getCardTransactions(); // on dump(), it works
$showMapper->tab('Cards')
->add('Data', 'string', array(
'template' => "#AdminTemplates/sonata/details.html.twig",
'card' => $card
))
->end()
->end();
}
and in my twig;
{% for c in card %}
{{ c.id }}
{% endfor %}
I think it has to do with SonataAdmin and how it handles this type of calls but I have read the documentation and searched online but still no luck.
You have to use the field_description.options object in your template to access your variable.
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->tab('Cards')
->add('Data', 'string', [
'template' => "#AdminTemplates/sonata/details.html.twig",
'card' => $this->getCardTransactions(),
])
->end();
}
{# #AdminTemplates/sonata/details.html.twig #}
{% extends '#SonataAdmin/CRUD/base_show_field.html.twig' %}
{%- block field -%}
{% spaceless %}
{% for card in field_description.options.cards %}
{{ card.id }}
{% else %}
<p>No card</p>
{% endfor %}
{% endspaceless %}
{%- endblock -%}

Twig for loop iteration

Array
(
[0] => Array
(
[product_id] => 49
[thumb] => http://192.168.0.101/user1/OPC_Fabish3.0/upload/image/cache/catalog/demo/banners/Productimage-278x355.jpg
[rollover_thumb] => http://192.168.0.101/user1/OPC_Fabish3.0/upload/image/cache/catalog/demo/banners/Productimage-278x355.jpg
[name] => tulip lamp family
[description] => Samsung Galaxy Tab 10.1, is the world’s thinnest tablet, measuring 8.6 mm thickness, running w..
[price] => $241.99
[special] =>
[tax] => $199.99
[rating] => 0
[href] => http://192.168.0.101/user1/OPC_Fabish3.0/upload/index.php?route=product/product&product_id=49
[model] => SAM1
)
)
This is my products array in PHP.
In twig I am fetching the values using the following code:
{% for j in 0..(products|length) %}
{% endfor %}
However I am not getting any result.
I suppose it is:
// or
Or simplier:
{% for product in products %}
{% endfor %}

loop through key values of an array in twig

I have not been able to find my answer elsewhere (maybe because I didn't know how to ask google as I'm pretty new to this ;))
I'm working with symfony and twig.
I pass an array in my view with only one entry related to the id. It looks like this in my view
array:2 [▼
"sponsor" => Sponsor {#473 ▼
-id: 5
-sponsorCode: "FUT"
-name: "MANULO"
-city: "OLERDOLA"
-zipCode: 0
-address: ""
-country: "ESPANA"
-phoneNumber: 32767
-email: ""
-creationDate: DateTime {#470 ▶}
}
"app" => AppVariable {#476 ▶}
]
I know I can access each property by doing
{{sponsor.name}}
But I'm trying to do it through a loop for each field of this array
something like
{% for key, value in sponsor %}
<div class="field-group">
<div class="field">{{ key }}:</div>
<div class="value">{{ value }}</div>
</div>
{% endfor %}
Am I missing something?
Thank you very much
From the TWIG documentation:
Keys Only
By default, a loop iterates over the values of the sequence. You can iterate on keys by using the keys filter:
<h1>Members</h1>
<ul>
{% for key in users|keys %}
<li>{{ key }}</li>
{% endfor %}
</ul>
Keys and Values
You can also access both keys and values:
<h1>Members</h1> <ul>
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %} </ul>
https://twig.sensiolabs.org/doc/2.x/tags/for.html
Keep your eye on the TWIG documentation, its rather comprehensive.
Looking at your code, it looks ok. However, the issue could be that the {{value}} may need further identification, such as {{ value.id }}

Resources