2

In Sprout Reports, I am creating a list of users in my settings file. I first need an option with value of null.

{% set options = [] %}
{% set options = options|merge([{ label: 'All users', value: null }]) %}
{% for user in users %}
  {% set fullname = user.firstName ~ " " ~ user.lastName %}
    {% set options = options|merge([{ label: fullname, value: user.id }]) %}
{% endfor %}

{{ forms.selectField({
    label: "Choose one"|t,
    name: "userId",
    options: options,
    }) 
}}

Then, in my index file (the report), I do something like this:

{% set purchases = craft.entries()
  .section('purchases')
  .authorId(settings.userId)
  .all()
%}

My query runs fine if there is a value for userId, but when it is null, the query does not return any results.

What am I doing wrong?

Do I need to do something like this?

3

Yes, the post you linked to is what you need to do.

I don't know where your settings variable is set so you may need to adjust a bit but something like this should get you started:

{# Start your element query #}
{% set query = craft
    .entries()
    .section('purchases')
%}

{# Check if settings.userId, if so, apply it to the query #}
{% if settings.userId %}
    {% set query = query.authorId(settings.userId) %}
{% endif %}

{# Run the query #}
{% set purchases = query.all() %}
1
  • Thanks, Oli. That does it. – 4midori Nov 11 '20 at 21:40

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.