3

How do you update an URL with new params?

I'm working on a search / filter entries page. I have multiple menu lists with categories in it. Like this:

Size: Small Medium Large

Color: Blue Red White Yellow

So if the URL is product?size=m and I click on a link "Size → Large" then the URL needs to update to product?size=m,l. Click again on "Large" the l value of the sizes parameter needs to delete.

If I then click on "Color → Red" the URL must be product?size=m,l&color=red.

  • So you actually want to know how to compose the parameters and not how you "update an URL". – carlcs Aug 26 '14 at 10:14
  • :-) yes. Sorry, my english isn't good – Johannes Lamers Aug 26 '14 at 10:17
4

I'd split the parameter string into an array and then loop through the categories and use a conditional to check if the value already exists in the parameter. It's not so easy to describe in detail, that's why I added lots of comments to the code (untested!).

To work in your other parameters (size, etc.), simply add them to your links exactly how craft.request.getParam() returns them. Conditionally skip the output completely if the param is empty.

{# Get the parameter (e.g. 'red,blue,black') #}
{% set currentParam = craft.request.getParam('color') %}

{# Split the parameter string #}
{% set arrCurrentParam = currentParam|split(',') %}

{# Loop through categories to output the links #}
{% for catOut in categories %}

    {# Define newParam var before loop #}
    {% set newParam = '' %}

    {# Loop through categories to compose the new parameter #}
    {% for catComp in categories %}

        {# Check if changes could happen in this loop #}
        {% if catOut.slug == catComp.slug %}

            {# Add category if it was currently NOT selected #}
            {% if catComp.slug not in arrCurrentParam %}
                {% set newParam = newParam ~ ',' ~ catComp.slug %}
            {% endif %}

        {% else %}

            {# Add category if it was already selected #}
            {% if catComp.slug in arrCurrentParam %}
                {% set newParam = newParam ~ ',' ~ catComp.slug %}
            {% endif %}

        {% endif %}

    {% endfor %}

    {# Remove leading comma #}
    {% set newParam = newParam|slice(1) %}

    {# Conditionally add param to link output #}
    <a href="product?{{ newParam ? 'color=' ~ newParam }}">{{ category.slug }}</a>

{% endfor %}
  • you made my day!!!! – Johannes Lamers Aug 26 '14 at 13:18
  • Glad I could help, @Johannes. It was a challenge to think that one through though! But yeah, I'm sure I need something similar sooner or later, so it was definitely worth it :) – carlcs Aug 26 '14 at 13:29
  • I think more crafters need this too. Thank you again! – Johannes Lamers Aug 26 '14 at 13:33

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.