6

Consider an employee listing...

I have 2 sections: 1 for companies, 1 for personnel. In the personnel section, there is a matrix field within which one field is a relational one to relate the staff member to his company.

On the front end, I'm attempting to display a listing of all staff associated with a particular company.

I can't seem to get the relational fields to work in the way that I want. I know I'm missing something basic here.

{% set employer = craft.entries.section('companies').slug(segment) %}
{% set personnel = craft.entries.section('people').relatedTo(employer) %}

{% for x in personnel %}
    {{ x.title }}
{% endfor %}

// Output: nothing

Is there something particular to Matrix fields that changes how I might do this? I've tried using the targetElement parameter but still can't seem to get it to work.

Thanks for the help!

7

When you relate an element from a Matrix block, it's important to know that the relation is between the Matrix block and the related element; nor the entry (or whatever has the Matrix field) and the related element.

So, the correct way to select related elements through a Matrix field is:

{% set employer = craft.entries.section('companies').slug(segment) %}
{% set personnel = craft.entries.section('people').relatedTo({
    targetElement: employer,
    field: "matrixField.relationField"
}) %}

Update: Added a missing } on the last line.

  • Thanks Brandon. Just getting up to speed with Craft. You guys are amazing! – V. Arora Oct 10 '14 at 3:37

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.