1

I'm using Commerce to sell tickets to an event and need to get the names of each person. I would like to do this via a Matrix field, showing fields based on the quantity selected.

I followed along with the new Sprigform tutorial, which covers part of it but it has an add button as opposed to a dropdown.

This is what I have so far, but on changing the select value the input field disappears, so maybe I'm just looping over things incorrectly?

{% set qty = qty ?? [['']] %}
<select sprig name="qty">
  {% for i in range(1, 5) %}
    <option value="{{ i }}" s-val:qty="{{ i }}" {{ qty == i ? 'selected' }}>{{ i }}</option>
  {% endfor %}
</select>
    
{% for guest in qty %}
  <input sprig type="text" name="options[guests[{{ loop.index0 }}][0]]">
{% endfor %}

Would appreciate any pointers!

1
  • Still massively struggling with this one. Am I just not understanding for loops properly?
    – supazu
    Mar 14, 2021 at 23:53

1 Answer 1

2
+50

The problem that you expect your qty variable to be an array of guests and initialize it like that, but once you set a quantity it will be an integer, so the loop won't work correctly. See this line:

{% set qty = qty ?? [['']] %}

This initializes qty to an array containing another array containing an empty string (by the way, why do you need the nested array? Wouldn't a simple array of guest names suffice?). But once you select a quantity, the qty variable will simply be an integer (or numeric string, not sure). A for-loop expects an iterable (array or iterable object), so your for-loop is invalid:

{% set qty = 3 %}

{# this is invalid #}
{% for guest in qty %}
    {# this will never be reached #}
{% endfor %}

Instead of qty, what you want is a guests variable which holds a number of items in your expected format (in this case, arrays of strings) corresponding to the selected quantity. For example:

{% set qty = qty ?? 1 %}
{% set guests = range(0, qty - 1)|map(i => ['']) %}

{% for guest in guests %}
  <input sprig type="text" name="options[guests[{{ loop.index0 }}][0]]">
{% endfor %}

Note this will reset the values in the guest input fields whenever the quantity is changed. You'd need to retrieve the current inputs as well to set the current values of the input fields as well.

1
  • 1
    That did it - thank you!
    – supazu
    Mar 31, 2021 at 3:26

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.