Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

For a url like domain.com/example/123 where 123 is a Matrix Block ID (not an Entry ID), can I get the associated entry for given block ID in a template?

Or, for a more general approach, what would be the best way to get that Matrix Block element and its Entry element when you only have a block ID?

Edit: so ideally:

{% set block = craft.matrixBlocks.id(craft.request.segment(2)).first() %}
{% set entry = block.getOwner() %}

...which isn't possible now.

share|improve this question
    
Is 123 the block ID or the block index? –  jpea Jul 9 at 13:45
    
The ID. Not the index. –  Low Jul 9 at 13:46
    
Gotcha - I posted something that might work below. I haven't tested it, but it's the gist of something that should work. –  jpea Jul 9 at 13:49

2 Answers 2

up vote 8 down vote accepted

At the time of this writing, the ideal solution isn't possible. But, as jpea suggested, creating a plugin was dead easy, so here it is:

Low Blocks

...which lets me use syntax like this:

{% set block = craft.lowBlocks.id(craft.request.segment(2)) %}
{% set entry = block.owner %}
share|improve this answer
    
Now that's the way to answer your own question, 4 hours later with the plugin you just wrote to solve it. ;) –  Simon Kuran Jul 9 at 18:00
    
Heck yeah - nice work! –  jpea Jul 9 at 18:53
    
Someday I'm going to answer my own question with my own plugin. Nicely done. –  Matt Stein Jul 9 at 21:06

Perhaps just grab the URL segment and set it as a variable:

{% set mID = craft.request.getSegment(2) %}
{% for entry in craft.entries.section('whatever') %}
   {% for block in entry.myMatrixField.id(mID) %}
     {{ block.someNestedFieldInsideOfMyMatrixField }}
   {% endfor %}
{% endfor %}
share|improve this answer
    
Yeah, I was hoping to avoid looping through every entry... –  Low Jul 9 at 13:49
2  
Actually, if I remember correctly one of the discussions I had with Brandon, this wouldn't be too taxing in terms of queries. Craft is smart enough to only fetch what it needs (the entry_id in this case) –  Jérôme Coupé Jul 9 at 13:51
    
Even with Yii's ORM, it still grabs the entries before it can grab the Matrix block. Ideally, yes, it would be great if there's an interface somehow directly into Matrix ID's. It wouldn't be a tough plugin to write though if there's no native way to do it. –  jpea Jul 9 at 15:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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