2

I'm trying to augment a Commerce query with additional parameters like so, but I can't get 'colour' and 'range' working together. Clearly my and/relatedTo syntax is wrong but how exactly?

  {% set colour = craft.app.request.getQueryParam('colour') ?? null %}
  {% set range = craft.app.request.getQueryParam('range') ?? null %}

  {% set query = {
    type: 'fabric',
    limit: 999,
    orderBy: 'defaultSku asc'
  } %}

  {% set query = colour is defined ? query|merge({ relatedTo: ['and', { targetElement: craft.categories.slug(colour) }]}) : query %}

  {% set query = range is defined ? query|merge({ relatedTo: ['and', { targetElement: craft.categories.slug(range) }]}) : query %}

  {% set swatches = craft.products(query).all() %}
  {% for swatch in swatches %}

(Also need to add further queries params for texture etc which are also related to categories)

1 Answer 1

2

I figured it out with help from https://craftcms.stackexchange.com/a/5339/7356

This could probably be further refined but...

  {# Get query parameters from URL #}
  {% set colour = craft.app.request.getQueryParam('colour') ?? null %}
  {% set range = craft.app.request.getQueryParam('range') ?? null %}
  {% set texture = craft.app.request.getQueryParam('texture') ?? null %}

  {# Tee up the product query #}
  {% set queryParams = [colour, range, texture] %}
  {% set hasValidQueryParams = false %}
  {% set relationParam = ['and'] %}
  {% set query = {
    type: 'fabric',
    limit: 999,
    orderBy: 'defaultSku asc'
  } %}

  {# Store any valid query parameters #}
  {% for param in queryParams %}
    {% if param != null %}
      {% set hasValidQueryParams = true %}
      {% set relationParam = relationParam|merge([{targetElement: craft.categories.slug(param) }]) %}
    {% endif %}
  {% endfor %}

  {# Merge query parameters into the main product query  #}
  {% if hasValidQueryParams %}
    {% set query = query|merge({relatedTo: relationParam}) %}
  {% endif %}

  {# Display the result  #}
  {% set swatches = craft.products(query).all() %}
  {% for swatch in swatches %}
    {% include 'range/_fabric_swatch' with { 'visible': true } %}
  {% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.