I am trying to set up a form with checkboxes that allows users to filter entries by selecting multiple categories, but I am not quite getting it right.
Currently this is my form:
{% set subcategoryParam = craft.request.getParam('subcategory') %}
{% set subcategories = craft.categories.group('partnerAreas').find() %}
<form action="{{ craft.request.url }}">
{% for subcategory in subcategories %}
<input type="checkbox" value="{{ subcategory.slug }}" id="{{ subcategory.slug }}" name="subcategory" {{ subcategory.slug in subcategoryParam ? 'checked'}}>
<label class="label__checkbox" for="{{ subcategory.slug }}">
{{ subcategory.title }}
</label>
{% endfor %}
<button type="submit">
Search
</button>
</form>
Submitting this form gets me URL query strings like this:
?subcategory=sourcing-local-products&subcategory=communication
When I am using craft.request.getParam('subcategory')
, only the last selected subcategory gets picked up (as you would expect).
I've tried setting the name on the checkbox field to subcategory[]
, but that gets me an array to string conversion
template error and the URL query string then looks like this:
?subcategory%5B%5D=sourcing-local-products&subcategory%5B%5D=communication
What do I need to do to get a comma separated list for the subcategory parameter like this:
?subcategory=sourcing-local-products,communication
And once that is working, how do I then get all the entries that have any of the selected categories assigned via a Matrix field?
This is what I've currently got:
{% set subcategoryParam = craft.request.getParam('subcategory') %}
{% set selectedSubcategories = craft.categories.slug(subcategoryParam) %}
{% set entries = craft.entries({
section: listingType,
relatedTo: {
targetElement: selectedSubcategories,
field: 'involvementAreas.area'
}
}) %}
But I imagine that's not quite right if I want to account for an array of selected categories...