1

There's a section called locations and another called vacancies. In vacancies the admin can assign a location entry to a vacancy.

On the careers overview page we want to display selected vacancies block.vacancySelected.

In the template we loop through all locations and would like to display the number of vacancies per location.

{% set lparas = {
    section: 'locations'
    } %}
{% set locations = craft.entries(lparas) %}

{% if locations | length %}
   {% for location in locations %}
      {% set cEntries = block.vacancySelected.relatedTo(location) %}
      {% if cEntries| length %}
         {{ location.locationName }} ({{ cEntries | length }})
      {% endif %}
   {% endfor %}
{% endif %}

But for some reason it shows all locations and the total number of vacancies per locations. It seems to ignore that we only want to show the locations of the selected vacancies.

  • Where does the block variable come from? – Robin Schambach Nov 7 '18 at 13:00
2

If I correctly understand your question, you want to show each location with at least one vacancy, and the number of vacancies for that location? I don't really get what block.vacancySelected is?

The way I would do this:

{# get all locations #}
{% set allLocations = craft.entries.section('locations').all() %}

{% for location in location %}
    {# get a vacancy count for this location #}
    {% set vacancyCountForLocation = craft.entries.section('vacancies').relatedTo({
        field: 'locationFieldHandle',
        targetElement: location,
    }).count() %}

    {% if vacancyCountForLocation %}
        {{ location.locationName }} ({{ vacancyCountForLocation }})
    {% endfor %}
{% endfor %}

To prevent loading all locations, even if they have no vacancies, you could also try (untested):

{# get all locations, but only if they have related vacancies #}
{% set allVacancies = craft.entries.section('vacancies').ids() %}
{% set allLocations = craft.entries.section('locations').relatedTo({
    field: 'locationFieldHandle',
    sourceElement: allVacancies,
}).all() %}

{% for location in location %}
    {# get a vacancy count for this location #}
    {% set vacancyCountForLocation = craft.entries.section('vacancies').relatedTo({
        field: 'locationFieldHandle',
        targetElement: location,
    }).count() %}

    {{ location.locationName }} ({{ vacancyCountForLocation }})
{% endfor %}
| improve this answer | |
  • Thank you, yes you understood it correctly. block.vacancySelected is a set of vacancies – we only want to show selected vacancies. We want to display each location with at least one of the selected vacancies. – user9247 Nov 8 '18 at 13:03

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.