We have a commerce site that provides samples of its items. We have a single product that handles all the samples and displays them in a dropdown. What I'd like to do is have a link on the product page that passes this product name/slug to the sample product. What would be the best way to approach this?

The sample product url is /samples/sample. I have tried something like Order a Sample. But that tries to look up a product with that url and it does not exist.

In the dropmenu I am trying

{% set prodSlug = craft.request.getLastSegment() %} 
{% for purchasable in product.variants %}
    {% set current = (product.slug == prodSlug) %}
       {% if current %} 
        <option {% if purchasable.stock <= 0 and purchasable.hasUnlimitedStock == false %}disabled {% endif %} value="{{ purchasable.id }}">
        {{ purchasable.description }}  {{ purchasable.price|commerceCurrency(cart.currency) }}</option>
       {% endif %}
{% endfor %}

Is there a way to setup a product that could accept different slugs to make this work? Maybe with a route?

1 Answer 1


Yep so can just create a route in the control panel.

See: https://docs.craftcms.com/v3/routing.html

You'll see you can use a slug (using the token slug) so that Craft will validate the url actually has a valid slug on the end, or you can just use * and craft will route to this template no matter what is on the end.

enter image description here

(I personally prefer to create routes in source control managed & commented code using the routes.php config file - https://docs.craftcms.com/v3/routing.html#advanced-routing-with-url-rules ... so this would be something like:

'samples/sample/<slug>' => ['template' => '/your/samples/template']

Then, on the main product page, build your url to the samples page as, basically:

/samples/sample/{{ thisProduct.slug }}

Then, in your samples template you just grab the last segment, as you are, and use that in your code to pre-select the particular sample from you list...as you are.

So basically, you're almost there apart from creating the route.

Your Answer

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

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