1

I have a Matrix field named "skillLevels" with a single block type. Each row has 2 fields, "skillName" and "skillLevel"

skillName is a relationship to another entry (Skills) skillLevel is a simple integer.

I am building a custom plugin which takes post data from a form. The form contains an entry ID ($groupId), a skill name and a value to use to modify the level of that skill.

$groupEntry = craft()->entries->getEntryById($groupId);

    $skillLevels = $groupEntry->skillLevels;

    foreach($skillLevels as $skill){
       $skillLevel = $skill->skillLevel; // outputs the skill level
       $skillName = $skill->skillName; // this doesn't work
    }

$skill->$skillLevel gives me the integer stored in that field. But $skill->skillLevel does not gives me a model. I then tried using $skill->skillLevel->id but still no luck.

How can I look through the Matrix rows to find the row that matches the skill name coming from the form Post data?

3

Your skillName is a object of type ElementCriteriaModel so it is just a query. In order to fetch the element you need to do $skill->skillName->first()

You should read the docs about how to fetch entries and how the elementCriteriaModel works.

Edit: your $skillLevels and your $skill->skillName are both the same type of objects. Both are ready to use queries that have a iterable interface. So when you loop through them (like you do) the find() method is executed which returns you all the populated query results. You don't load all relations for an entry when you do getEntryById - you get just queries you can execute

  • I'd read the docs. I realised about 10 minutes after posting this that I needed to iterate through skillName or use first(). Thanks – foamcow Nov 28 '17 at 17:19
  • Seems like my edit was wasted time then. This works for every relation.. Images, users, all assets, categories, even matrix fields are only relations. No matter what you relate you always get a criteriamodel unless you specify it otherwise. It can be a little bit confusing at the first time – Robin Schambach Nov 28 '17 at 17:22
  • Thanks, it's all helpful. I knew that it returned a model but I didn't make the connection that i needed to iterate through it. Dumb because I've done it before! – foamcow Nov 28 '17 at 17:25
3

It’s an entries field, so $skill->skillName returns just the ElementCriteriaModel prepared to query for one or more elements matching the criteria.

You need to do something like this:

$entry = $skill->skillName->first();
$skillName = $entry ? $entry->title : null;

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.