1

Within a frontend Add Product form (using Craft Commerce) I'm having problems with a database error whenever a Users field is left empty.

Here's the field:

{% set teachers = craft.users.group('teachers') %}
<select name="fields[teacher][]">
<option value="">n/a</option>
{% for teacher in teachers %}
  <option value="{{ teacher.id }}">{{ teacher.name }}</option>
{% endfor %}
</select>

I've tried setting the empty value to zero, but no luck. The forms works fine apart from this, so I don't think it's anything specific to Craft Commerce.

2

Figured it out. If you want to return an empty Users field, the field name attribute has to look like this:

<select name="fields[teacher]" value="">

But if you want to return a non-empty Users field, the name attribute is different:

<select name="fields[teacher][]" value="{user.id}">

So, I'm starting with the first example, and using an onChange event to switch the name attribute depending on whether the value is a valid user ID or not. Here's my final template code:

{% set teachers = craft.users.group('teachers') %}
<select class="ui search dropdown" name="fields[teacher]" id="teacherselect">
<option value="nA">n/a</option>
{% for teacher in teachers %}
  <option value="{{ teacher.id }}">{{ teacher.name }}</option>
{% endfor %}
</select>

And the jquery if anyone wants it:

($(this).val() == "nA") ? $(this).attr('name', 'fields[teacher]') : $(this).attr('name', 'fields[teacher][]')

This works.

1

Yep, seen this before. You can't just have an empty value like that because the validation stuff just sees it as a missing field that's required to not be missing. We got around it by adding the n/a value into the field itself in the back end of Craft.

Which doesn't help you for User Groups unless you want to create an 'n/a' group.

  • Thanks Matt. Have figured this out - the name attribute is different when the field is empty. – Clive Portman Oct 27 '16 at 11:31

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.