1

This is my code I am using, but want to limit it to just one and possibly randomize it also. Is it possible with Table, I looked at the example on Craft's site but did not see that option.

{% for row in block.example %}
    {{ row.examplerow }}
{% endfor %} 
2
  • 1
    Have a look at: stackoverflow.com/a/38677493/26130
    – Brad
    Commented Apr 25, 2017 at 20:12
  • Brad that is something I tried before but it errors as an unknown filter shuffle. I did take out the shuffle and tried just slice(0,1) and it worked. Just need the random part now.
    – Vin
    Commented Apr 25, 2017 at 20:28

1 Answer 1

3

I have never tried it on a table field, but you could try:

{% for row in block.example.limit('1').order('RAND()') %}
    {{ row.examplerow }}
{% endfor %} 

OK, above will not work. I went back on my theory and actually tried it on a table field I had laying around. This worked for me:

{% set rows = shuffle(block.example) %}

{% for row in rows | slice(0, 1) %}
   {{ row.examplerow }}
{% endfor %}
6
  • If that does work, and returns a single row, you wouldn't need the for loop. Commented Apr 25, 2017 at 19:12
  • Thanks for that AbbeyDesign, I tried that and now it returns no records.
    – Vin
    Commented Apr 25, 2017 at 19:43
  • What kind of field is it that you are trying to loop through? Commented Apr 25, 2017 at 19:57
  • Trying to loop through a Table field in Matrix.
    – Vin
    Commented Apr 25, 2017 at 20:28
  • 1
    @Vin I edited the code above. Let me know if that works. I tried it on a table field I had and it worked for me. Commented Apr 25, 2017 at 20:53

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.