1

Excuse my new-ness, but I'm having an issue with product variants.

Scenario

I have a product with multiple variants (up to 30 in fact). Based on the URL, I want to choose a specific variant so that I can display fields from that variant on my product detail page. I also want a 'default variant' if there is no variant specified in the URL.

In my example, the variant should be selected by a custom field in that variant colour whose value match the 4th URL segment.

Code

{# Grab colour segment #}
{% set colourSlug = craft.request.getSegment(4) %}

{# If there is no colour, we grab the first variant colour #}
    {% if not colourSlug %}
        {# Grab first product variant #}
        {% set dressColour = product.defaultVariant %}
    {% else %}
        {# Set dress colour #}
        ??{% set dressColour = product.variants.find(colour.colourSlug) %}??
    {% endif %}
2

You would currently need to loop over all variants and just grab the ones that match the 'if' condition shown below:

{% set colourSlug = craft.request.getSegment(4) %}

{% if not colourSlug %}
    {# Grab first product variant #}
    {% set dressColour = product.defaultVariant %}
{% else %}
    {# Set dress colour #}
    {% for variant in product.variants %}
    {% if variant.colour == colorSlug %}
       {{variant.sku}}
    {% endif %}
    {% endfor %}
{% endif %}

We will look to enable variants to be an element criteria query. If each variant has their own page, would it make sense they are seperate products?

1

Just before I saw luke's answer I wrote this:

{# Grab colour segment #}
{% set colourSlug = craft.request.getSegment(4) %}

{# If there is no colour, we grab the first variant colour #}
    {% if not colourSlug %}
        {# Grab first product variant #}
        {% set dressVariantActive = product.defaultVariant %}
    {% else %}
        {# Set outside the loop #}
        {% set dressVariantActive = '' %}

        {% for dressVariantSelected in product.variants %}
            {% if dressVariantSelected.colour.value == colourSlug %}
                {% set dressVariantActive = dressVariantSelected %}
            {% endif %}
        {% endfor %}
        {% if not dressVariantActive %}{% exit 404 %}{% endif %}
    {% endif %}

I wanted to include this as I found out a useful thing: Defining a variable inside a for loop is only possible if you set the variable before the loop.

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.