1

I'm working on a site with some filters that result in a page with a URL similar to this: domain.com/led-products?series=67&efficacy=1000to5000&lumens=over150

That results page contains buttons/links like so:

[Series Name x] [1,000 to 5,000 Efficacy x] [Over 150 Lumens x]

Clicking on one of those would remove that filter. Let's say a user clicks on Series Name to remove that filter, the resulting URL would then be: domain.com/led-products?efficacy=1000to5000&lumens=over150

My problem is that I have no idea how to get that filter/parameter removal functionality in Craft. Does this require a JS solution?

I've played around with something like this and can't seem to get it to work for my needs.

Help?

  • 1
    Are you trying to do this with javascript, or just reload the page with the modified query string? – Dalton Rooney May 12 at 22:36
  • Honestly, whatever is going to be easiest. I'm totally fine with reloading the page with the modified query string. – Angie Herrera May 13 at 2:29
1

OK, this should be a working code example:

{% set queryParams = craft.app.request.queryParams %}
{% for key, value in queryParams %}
  {% set url = siteUrl ~ craft.app.request.fullPath %}
  {% set arr = queryParams | filter((v, k) => k != key) %}
  {% if arr|length > 0 %} 
    {% set url = url ~ '?' ~ arr|url_encode %}
  {% endif %}
  <a href="{{url}}">{{key}} {{value}} x</a>
{% endfor %}

Line by line:

Create an array based on the current request parameters:

{% set queryParams = craft.app.request.queryParams %}

Loop through the array and get the key/value pair:

{% for key, value in queryParams %}

While inside the loop, get the URL that we want to modify, minus the request params:

{% set url = siteUrl ~ craft.app.request.fullPath %}

Filter a local copy of the array to remove the current key:

{% set arr = queryParams | filter((v, k) => k != key) %}

If there are any parameters left, modify the URL we previously set with the remaining parameters:

{% if arr|length > 0 %} 
  {% set url = url ~ '?' ~ arr|url_encode %}
{% endif %}

Output the link that will load the page without the current parameter.

<a href="{{url}}">{{key}} {{value}} x</a>

I would probably do this in a macro to keep the template code a bit cleaner and easy to read.

| improve this answer | |
  • THANK YOU!! This worked great! There's one tiny thing I had a question on: p=page-slug is added to the URL. I get why and it's not critical at all, but is there a way to remove that at all? Again, no biggie! – Angie Herrera May 14 at 1:53
  • Hmm, I'm not sure, I didn't see that when I was testing this out. But the filter function does accept multiple conditions so this might work: {% set arr = queryParams | filter((v, k) => k != key and k != 'p') %} – Dalton Rooney May 14 at 22:44

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.