If you have two fields and want to validate that at least one of them is filled and then want to set an error on both of them but only print one message, you won't get a red box around the second field if you give form_set_error() an empty message. This is because _form_set_class() does if (form_get_error()) instead of checking NULL. I put in !is_null() instead of setting the value to $error then checking isset($error) to keep it all inline, but could be easily changed.

I think this should be applied to 5.x too.

if (empty($item['foo']) && empty($item['bar'])) {
  form_set_error('foo', t('You must enter at least foo or bar.'));
  form_set_error('bar', '');
}
CommentFileSizeAuthor
form.inc__1.patch593 bytesRobRoy

Comments

keith.smith’s picture

Status: Needs review » Needs work

patch no longer applies

# patch -p0 < form.inc__1.patch
patching file includes/form.inc
Hunk #1 FAILED at 1600.
1 out of 1 hunk FAILED -- saving rejects to file includes/form.inc.rej

ms2011’s picture

+1 for the ability to use form_error() without the second [optional] argument to merely flag fields with the .error class without having to print a message once per field. In my case, I have a group of 3 fields; if one is filled, the other two have to be, as well. I only need and want to display one error message, not three.

I came up with a different solution to this.

Just change:

/**
 * Return the error message filed against the form with the specified name.
 */
function form_get_error($element) {
  $form = form_set_error();
  $key = $element['#parents'][0];
  if (isset($form[$key])) {
    return $form[$key];
  }
  $key = implode('][', $element['#parents']);
  if (isset($form[$key])) {
    return $form[$key];
  }
}

to:

/**
 * Return the error message filed against the form with the specified name.
 */
function form_get_error($element) {
  $form = form_set_error();
  $key = $element['#parents'][0];
  if (isset($form[$key])) {
    return TRUE;
  }
  $key = implode('][', $element['#parents']);
  if (isset($form[$key])) {
    return $form[$key];
  }
}

Since form_get_error() is only ever used in one place and it doesn't matter what the return value is in that case as long as it does not evaluate to FALSE or empty().

This way you don't even have to include the second argument as a NULL or empty string '' at all when using form_error().

A minor change for major flexibility and convenience. :)

pwolanin’s picture

Version: 6.x-dev » 7.x-dev
Priority: Minor » Normal

I jsut ran into this in D7 - I think it's more than minor

pwolanin’s picture

pwolanin’s picture

Status: Needs work » Closed (duplicate)