Drupal: Highlight errors in fieldset with form_set_error()

Using form_set_error() to display error messages, the first argument is the name of a field.

$form['height'] = array(
  '#type' => 'textfield',
  '#title' => 'Height',
);

Along with:

form_set_error('height', 'Error with height.');

image

Normally this is simple to define, but when using nested form items within fieldsets, this doesn't highlight the right item.

If the form was changed to nest the items:

$form['new'] = array(
  '#type' => 'fieldset',
  '#title' => 'New Image Size',
  '#tree' => true,
);

$form['new']['height'] = array(
  '#type' => 'textfield',
  '#title' => 'Height',
);

Using:

form_set_error('height', 'Error with height.');

image

Notice the height is no longer highlighted?

The reason is that the field argument requires some formatting to make it work with nested forms.

Using a stupid '][' to tokenise the fieldname, we can specify which item to highlight.

form_set_error('new][height', 'Error with nested height.');

image

This gives us the proper feedback we wanted.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog