1

I've been referring to this question (can't comment as I don't have enough cred) — The most popular answer works, but I can't for the life of me figure out why Brad's version doesn't. When I try I get the following error:

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

{# Not Working (Brad's version) #}
{% set notWorkingUserId = craft.request.getSegment(2) %}
{% set notWorkingUser = craft.users.id(notWorkingUserId) %}

{# Working #}
{% set workingUser = craft.users.username( craft.request.segment(2) ).first() %}


{% block content %}

    <h1>Not Working: {{ notWorkingUser.email }}</h1>
    <h1>Working: {{ workingUser.email }}</h1>

    {{notWorkingUser}} {# Throws an error #}
    {{workingUser}}

{% endblock %}

I'm using the dynamic url routing mentioned in the most popular example, with the username. I also tried:

craft.users.username(notWorkingUserId)

Which throws the same error.

Now as far as I understand it (I've only been working with Craft for a short period), .first() is only required when it's an array. But Brad's version is passing the actual ID so shouldn't be required?

Can anyone explain this in simple terms? Craft is great, but for beginners it can get a bit confusing.

1

.first() is going to be required... I updated the answer in the original question, but here it is for posterity, too:

{% set notWorkingUserId = craft.request.getSegment(2) %}
{% set notWorkingUser = craft.users.id(notWorkingUserId).first() %}

Then you can access the properties of that user because it's a proper UserModel now:

notWorkingUser.email
  • Ah brilliant thanks, good to know it's not me going insane. Could you provide a link to the docs as to why .first() is required please? As to my mind it isn't an array — right? Or is it? – Rob Jul 20 '15 at 21:34
  • There's a good explanation on it here: craftcms.stackexchange.com/a/271/57 – Brad Bell Jul 20 '15 at 22:26

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.