Drupal: Highlight errors in fieldset with form_set_error()

0 Comments

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

1.$form['height'] = array(   
2.  '#type' => 'textfield',    
3.  '#title' => 'Height',    
4.);

Along with:

1.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:

01.$form['new'] = array(   
02.  '#type' => 'fieldset',    
03.  '#title' => 'New Image Size',    
04.  '#tree' => true,    
05.);    
06.      
07.$form['new']['height'] = array(    
08.  '#type' => 'textfield',    
09.  '#title' => 'Height',    
10.);

Using:

1.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.

1.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