If you generate a form by API and include a field of type "radios", and set "#required" to true, and the user submits the form without selecting one of the options, you get a very vague error message:

An illegal choice has been detected. Please contact the site administrator.

There is no indication what's the problem, nothing points to this field, instead, I gather this message is intended to report site configuration problems. which, obviously, isn't the case here.

The solution is to check if the "radios" group has a value, and if it doesn't, show an appropriate message, like the standard "!name field is required.".

Note: This error doesn't occur if there is an option in the '#options' array with index 0, because that option is selected by default. Since I want to force my users to think about their choice I do not want to pick a choice for them. So that is a non-solution.

Attachment: a demo module demonstrating the issue.

CommentFileSizeAuthor
#1 form.inc_.patch853 bytesbartl
bug_example.module.txt1.46 KBbartl

Comments

bartl’s picture

StatusFileSize
new853 bytes

Some further experimentation shows that if I provide an option with key the empty string, this one gets treated as "no option" and normal "element required" validation works. Of course, this also implies that this extra radio button also shows up (which may not be a bad thing).

Anyway, it seems like I've been able to produce a patch that works. BTW this is the latest production version of Drupal, Drupal 7.9. Apply in "includes" subdirectory with -p1.

Anonymous’s picture

You can always create a n/a button w/ key '0' and hide it with css using the first-child pseudo-selector. Then set it to be the default choice and validate against it with '0' throwing a friendly error.

chx’s picture

Project: Core development » Drupal core
Version: » 8.x-dev
Component: Code » forms system
Status: Active » Closed (duplicate)