I have a Matrix field which contains a bunch of blocks. If only one matrix field is present in the entry I need it to show a message. If more then one matrix field show an other message.

Below is my current code.

{% for block in entry.modelIds.limit(1) %}
    {% if block.modelId|length == 1 %}
        I am link - {{block.modelId}} <br>
    {% else %}
        Not a Link - {{block.modelId}}<br>
    {% endif %}
{% endfor %}

Any help would be appreciated. I have tried a few different approaches and am just stumped.


Edit: adding image of fields. enter image description here

  • "If only one matrix field is present" Do you mean "matrix block" there? I assume modelIds is the Matrix field, what type of field is modelId? – Brad Bell Mar 3 '16 at 20:13
  • modelIds is the matrix field name. block.modelId is a plain text field within modelIds. I hope this helps. – johnHoysa Mar 3 '16 at 21:07
  • So correct me if I'm wrong: if a Matrix block has 1 field show message A, if it has more than one field show message B? – Brad Bell Mar 4 '16 at 0:06
  • That is/was correct. Now that I am thinking about it, what I want to check for is if there is only one modelIds per entry not individual modelId. I need to update my example code! Thanks for helping me figure out that I was testing for the wrong element. Update coming soon. – johnHoysa Mar 4 '16 at 14:54

Thanks to Brad for asking me a question above, it made me realize I was checking for matrix fields and not the matrix block. My code is now working that I am checking for the correct element on the page.

Revised code:

{% if entry.modelIds|length == 1 %}
     I am link - {{block.modelId}} <br>
{% else %}
     Not a Link - {{block.modelId}}<br>
{% endif %}

Thanks Brad for the help!

| improve this answer | |

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.