2

I have a section with an text field and an image field. the asset field may sometimes be left blank. in this case, in my template, i want to grab the image from another random entry.

This is the code I'm trying to use, but when the image field is blank in my initial entry, I'm getting an error that Variable "image" doesn't exist. Am I calling the random image incorrectly?

{% for stat in craft.entries.section('statistics').limit(1).order('RAND()') %}
{% if stat.image|length %}
    {% set image = stat.image.first() %}
{% else %}  
    {% for random in craft.entries.section('statistics').limit(1).image(':notempty:').order('RAND()') %}
        {% set image = random.image.first() %}
    {% endfor %}
{% endif %}

{{ image.url('medium') }}')

{% endfor %}
2
  • 1
    Is there a reason you can't only get stats with images? Something like {% set stat = craft.entries.section('statistics'.limit(1).order('RAND()')).image(':notempty') %} May 22, 2017 at 23:38
  • That would be ideal, but there are way more stats than images, so in this case it's not realistic for the client to require an image for every stat.
    – artmem
    May 24, 2017 at 0:10

1 Answer 1

2

I think something like this should work

{# First get all the stats #}
{% set stats = craft.entries.section('statistics') %}

{# iterate over those stat in a random order %}
{% for stat in stats.order('RAND()') %}

    {% if stat.image | length %}

        {% set image = stat.image.first %}

    {% else %}

        {# If there's no image, query for a random stat, excluding those without images #}
        {% set randomStat = stats.image(':notempty:').limit(1).order('RAND()') %}
        {% set image = randomStat.first.image.first %}

    {% endif %}

{% endfor %}
5
  • Seems like that should work, but I get this error: Impossible to invoke a method ("first") on a string variable (":notempty:").
    – artmem
    May 25, 2017 at 16:34
  • Can you dump randomStat.image to see what's being returned there? It seems like it's not returning an asset model for some reason. May 29, 2017 at 22:43
  • When i dump randomStat.image, I get this: string(10) ":notempty:" string(10) ":notempty:" string(10) ":notempty:" string(10) ":notempty:" string(10) ":notempty:" string(10) ":notempty:"
    – artmem
    May 31, 2017 at 13:56
  • Interesting, I'm not totally sure what's happening here. Just to confirm, what version of Craft are you using? Jun 6, 2017 at 1:02
  • I'm using 2.6.2981
    – artmem
    Jun 6, 2017 at 17:35

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.