1

I want to get the title of the first element from a entries field in a for loop. I think its easier to understand with a code example:

{% set programs = craft.entries.section('program_point').block.first().title('first-block') %}
{% for program in programs %}
...
{% endfor %}

block is an entries field. And the loop should only consider entries where the title of the first element in blockis first-block.

When I tried this, I always got an error:

Impossible to invoke a method ("title") on a null variable

But when I did this:

{% set programs = craft.entries.section('program_point') %}
{% for program in programs %}
        {% if program.block.first().title == 'first-block' %}
             ...
        {% endif %}
{% endfor %}

all worked fine. So how can I check the title of the first element in the for loop?

4
  • Have you tried to put .first() before .block ? I think it has something to do with the order of this line.
    – KSPR
    Commented Apr 6, 2016 at 12:29
  • I think this returns the first entry of the section program_point. But I need the first element of block. Commented Apr 6, 2016 at 12:43
  • Yeah you're right. What about adding .find() at the end?
    – KSPR
    Commented Apr 6, 2016 at 14:59
  • Sadly the same result Commented Apr 6, 2016 at 15:14

1 Answer 1

1

I could be not following correctly, so I apologize if I'm way off here.

If you want to grab all entries that are selected in your block field, but only want to single out the first one, you could do something like this:

<h2>Program Points</h2>
{% for entry in craft.entries.section('program_point') %}
    {% if loop.first %}
        <h1>{{ entry.title }}</h1>
    {% else %}
        <h3>{{ entry.title }}</h3>
    {% endif %}
{% endfor %}

The twig for loop has some pretty cool stuff built in that you could leverage to check for the first entry.

Hope this helps!

3
  • Thanks for the answer! But I think this is not what I'm searching for. I only want the entries where the first element in block has the title 'first-block'. Maybe now you understand what I mean? Commented Apr 6, 2016 at 15:17
  • Will you be having more than one entry with a title of first-block?
    – Damon
    Commented Apr 6, 2016 at 15:27
  • yes i will have Commented Apr 6, 2016 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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