3

I need display Stores by Region, by example:

  • Alabama

    • Store X
    • Store Y
  • Idaho

    • Store A
    • Store B

So:

  • I create two channels Stores and Regions.
  • In the channel Stores I create a entries field type called storesRegion and check Regions source.

craft control panel

So great! I can create new stores and select where the store is located.

enter image description here

I can display the Regions like this:

{% set relatedRegions = craft.entries.section('regions').relatedTo({
    sourceElement: stores,
    field: 'storesRegion'
}) %}

{% for region in relatedRegions %}
    {{ region }}
{% endfor %}

good but now I need display all the Stores from each Region

this is a good example of what I need: https://www.apple.com/retail/storelist/

this is something related with reverse relations?

2

You could loop all regions and select their corresponding stores

{# you can as well include eager loading here #}
{% for region in craft.entries.section('regions').storesRegion(':notempty:').all() %}
    {% set storesForRegion = craft.entries.section('stores').relatedTo({
        targetElement: region,
        field: 'storesRegion'
    }).all() %}
    {{ region.title }}
    {% for store in storesForRegion %}
        {{ store.title }}
    {% endfor %}
{% endfor %}

If you want to increase your performance you can use eager loading at this point and include with(['storesRegion']) to your region Query

  • works!, I just remove from line2 .storesRegion(':notempty:') and add to line6 {% if storesForRegion|length %} – user6227766 Aug 1 '18 at 4:26
  • I would not recommend it since it uses deprecated behavior that may be removed but if you feel good with it ¯_(ツ)_/¯ – Robin Schambach Aug 1 '18 at 7:17
  • I just modify a little your code because yours won't display anything, no errors but no stores, white page, check the working code. thanks – user6227766 Aug 2 '18 at 0:53
0

Working Code:

{% for region in craft.entries.section('regions').all() %} {% set storesForRegion = craft.entries.section('stores').relatedTo({ targetElement: region, field: 'storesRegion' }).all() %} {% if storesForRegion|length %} {{ region.title }} {% for store in storesForRegion %} <a href="{{ store.url }}"> {{ store.title }} </a> {% endfor %} {% endif %} {% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.