1

I'm having trouble getting what should be a simple relationship between 2 channels to work as expected.

This is how things are set up.

Channel: Apprenticeships - essentially categories, types of apprenticeship (health, construction, catering etc)

Channel: Vacancies - individual apprenticeship courses - each one related to an Apprenticehips entry.

In my template I can show a list of all Vacancy entries with

{% set vacancies = craft.entries.section("vacancies").find() %}

Then loop through them and output field data. This works fine and shows all the vacancy entries.

But I want to be able to filter the entries returned to those that are related to a specific Apprenticeships entry. This filtering is to be based on the third url segment, which is the slug of the Apprenticeship entry.

{% for cat in craft.entries.title(craft.entries.slug(craft.request.segment(3)).limit(1).find()) %}

This works fine and I can output field data from that Apprenticeship entry. Proving, in my mind, that Craft knows which entry I want.

To get only the Vacancy entries that are related to the Apprenticeship entry represented by cat I thought I could simply use 'cat' in another craft.entries tag.

{% set vacancies = craft.entries.section("vacancies").relatedTo(cat) %}

Then loop through vacancies outputting the vacancy field data. But it doesn't return any Vacancy entries even though there definitely some to return.

Where am I going wrong here?

2

I recommend doing it like so:

{% set vacancies = craft.entries.section('vacancies').limit(null) %}

{% set catSlug = craft.request.segment(3) %}

{% if catSlug %}
    {% set cat = craft.entries.section('apprenticeships').slug(catSlug).first() %}

    {% if cat %}
        {% set vacancies = vacancies.relatedTo(cat) %}
    {% endif %}
{% endif %}

This sets up an ElementCriteriaModel for all your Vacancies entries (don't use the find() method yet!). Then checks for the first entry from the Apprenticeships section with a slug of your URL segment. If there's really such an entry, it further extends the ElementCriteriaModel with a relatedTo parameter.

  • I'm afraid this doesn't work either. In this case when a third segment is present it returns all the vacancies (related or not). When there is no third segment it shows nothing. – foamcow Oct 8 '15 at 15:40
  • If I alter your code and use {% if catSlug %} {% set cat = craft.entries.slug(catSlug).first() %} {% endif %} then I get all vacancies when there is no third segment but nothing when there is a third segment. – foamcow Oct 8 '15 at 15:47
  • and yes, I am on Craft Slack – foamcow Oct 8 '15 at 15:47
  • This works perfectly. Part of the problem was my original code but the biggest issue was me testing with the wrong url! – foamcow Oct 8 '15 at 16:15

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.