1

I am using the Sprig plugin to filter news entries on a news overview page. I have three checkboxes for the categories related to the news entries.

I have the page working for the basic functions by adapting code used on the Sprigboard.

But the page won't let me select multiple checkboxes. I can't figure out how to make Sprig respect all checkboxes and push the selection to the url.

I have previously done this using vanilla javascript, but I wonder if such a feature could be solved elegantly using Sprig.

Category checkboxes:

  {% for category in craft.categories().group('news').all() %}
  <li class="filter--content--item {{ category.id in newsCat ? 'selected' : '' }}">
      <input sprig type="checkbox" class="filter_checkbox" name="newsCat" id="checkbox_{{ category.id }}" value="{{ category.id }}" {{ category.id in newsCat ? 'checked' : '' }}>
      <label id="label_{{ category.id }}" class="newsCatLabel" for="checkbox_{{ category.id }}">
          {{ category.title }}
      </label>
  </li>
  {% endfor %}

Search query:

  {% set newsCat = newsCat ?? '' %}
  {% set relatedTo = newsCat ? relatedTo|merge([newsCat]) : relatedTo %}

  {% set entryQuery = craft.entries
    .section('news')
    .limit(10)
    .relatedTo(relatedTo)
    .search(search)
  %}
  (...)
  {% do sprig.pushUrl('?' ~ {page: page, newsCat: newsCat}|url_encode) %}
2

Checkbox input field names should be in array format (not specific to Sprig), so I expect this should work.

<input sprig type="checkbox" class="filter_checkbox" name="newsCat[]" id="checkbox_{{ category.id }}" value="{{ category.id }}" {{ category.id in newsCat ? 'checked' : '' }}>
2
  • That ended up in always using newsCat[0], which I tried early. Based on your input, and since you believed it should work, I investigated further and got it working using below code. Thanks! – MisterMike Mar 10 at 7:30
  • Glad to hear it! – Ben Croker Mar 10 at 8:25
1

I ended up using the following code - I just didn't come up with it earlier. I had to index the newsCat array used to denominate the single checkbox names.


{% set newsCat = newsCat ?? '' %}
{% set relatedTo = newsCat|join(',') %}

{% set entryQuery = craft.entries
    .section('news')
    .limit(5)
    .relatedTo(relatedTo)
%}


{% for category in craft.categories().group('news').all() %}
    <li>
        <input sprig type="checkbox" name="newsCat[{{ loop.index}}]" value="{{ category.id }}" {{ category.id in newsCat ? 'checked' :'' }}>
        <label for="checkbox_{{ category.id }}">
            {{ category.title }}
        </label>
    </li>
{% endfor %}

{% do sprig.pushUrl('?' ~ {page:page, newsCat:relatedTo}|url_encode) %}

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.