0

I'm new to Craft and am trying to set up a condition that will compare the value of a category (entry.position). However, I get this error message:

Object of class Craft\ElementCriteriaModel could not be converted to string

I'm not really sure how to do a textual comparison. The 'position' field is, in my case, a category. How would a comparison be achieved?

I've tried this:

{% set entry_pos = entry.position %}
{#   {%  craft.categories.slug('position') %} #}                 
{{ entry_pos }}

{% if entry.position != 'staff' %}
    {% if entry.UBFUserName != '' %}
        {% set name_var = entry.UBFUserName %}
            {{ craft.aitest.AiTestVariable(name_var) }}
        {% else %}
    {% endif %}      
{% endif %}
2

Your entry_pos is an Element Criteria Model. You want to get the first (and probably only) category from this ElementCriteriaModel, and then compare its title to 'staff':

{% set entry_pos = entry.position.first %}
{% if entry_pos.title == 'staff' %}
  ...
{% endif %}

This will give you an error if there is no entry.position.first, as entry_pos will be null, so you should defend against that somehow. One possility is:

{% if entry_pos and entry_pos.title == 'staff' %} ...

Another is to use twigs useful null-coalescing operator:

{% if (entry_pos.title ?? '') == 'staff' %} ...

With Craft 3, you will use one instead of first, but otherwise everything is the same.

|improve this answer|||||
  • Would parentheses be needed in the compound conditional statement (above)? For some reason, the if/then statement is returning 'yes' to both 'staff' and 'faculty'. – buck1112 Apr 12 '18 at 16:14
  • I'm not sure if the ()'s are needed - depends on twig operator precedence. – Marion Newlevant Apr 13 '18 at 11:06
  • Thanks. That did the job - I added 'lower' to it to fix the remainder of the problem. {% if entry_pos and (entry_pos.title|lower != 'staff') %} – buck1112 Apr 20 '18 at 21:02

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.