In my cart (Craft3/Commerce2), I need to show a line item's possible options from a checkbox field called "productOptions", and allow the user to select the desired options.

Based on the Craft Docs, I can manually test if an item.options exists, but this means hard-coding the list of possible options(35+) into the cart, and keeping that updated as available options change:

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/update-line-item">
    {{ redirectInput('cart') }}
    {{ csrfInput() }}
    <input type="hidden" name="lineItemId" value="{{ }}">
    <span {% if item.getFirstError('qty') %}class="has-error"{% endif %}>
    <input type="number" name="qty" min="1" value="{{ item.qty }}"></span>

{#  Manual List of Options to Test if Exists #}
    {% if item.options.optionOne is defined %}
        <label class="checkbox">
            <input type="checkbox" name="options[optionOne]" checked> Option One 
    {% endif %}
    {% if item.options.optionTwo is defined %}
        <label class="checkbox">
            <input type="checkbox" name="options[optionTwo]" checked> Option Two 
    {% endif %}

OR, I can output the list of product options available for a given product, and use that to update the cart:

{#  To access the product options, set a variable "product" #}
    {% set product = item.purchasable.product %}
    {% for key, value in product.productOptions %}

        <label class="checkbox">
{#          <input type="hidden" name="options[{{ value }}]" value=""> #}<!-- uncheck it if not checked -->
            <input type="checkbox"  name="options[{{ value }}]" value="on" 
            {% if item.options.value is defined %}checked{% endif %}> {{ value }} 

    {% endfor %}

    <input type="submit" class="button" value="Update"/>

But I can't seem to figure out how to test if the checkbox is selected/value =="on" from the cart array. I know that {% if item.options.value is defined %}checked{% endif %} is not the correct way to access this value if it even can be accessed in this for loop.

Help? Many thanks in advance!

{% if item.options.value is defined and item.options.value == 'on' %}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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