Skip to main content

Adding HTML elements to a Drupal 7 submit button

Today I needed to add the html character "»" to a Drupal 7 form value. The first thing I did was alter the form and add the » character to the end of the submit button's value. Upon reloading the form, I noticed that instead of the character being displayed, the plaintext was displayed.

After doing a bit of searching I found the theme_button() function which was using the drupal_attributes() function to build the attributes for the submit button. Upon further inspection of drupal_attributes(), I discovered that all attributes were being run through Drupal's check_plain() function and making everything plain text. This is a good thing 99% of the time, but not for adding html to the submit button.

Solution

To make this work I needed to override the theme_button() function and force my html element onto the proper button. The code looks like this:

  1. function MYTHEME_button($variables) {
  2.  
  3.   $element = $variables['element'];
  4.   $element['#attributes']['type'] = 'submit';
  5.   element_set_attributes($element, array('id', 'name', 'value'));
  6.  
  7.   $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  8.   if (!empty($element['#attributes']['disabled'])) {
  9.     $element['#attributes']['class'][] = 'form-button-disabled';
  10.   }
  11.  
  12.   // Check if this is the element we want to add our HTML $raquo; to.
  13.   if($element['#id'] == 'edit-submit-vendor-inspector-providers') {
  14.     $attributes = $element['#attributes'];
  15.     // Loop through the $attributes and find the 'value' attribute.
  16.     foreach ($attributes as $attribute => &$data) {
  17.       $data = implode(' ', (array) $data);
  18.       if($attribute == 'value') {
  19.         // Run the value through check_plain and then append our » to the end of the value.
  20.         $data = $attribute . '="' . check_plain($data) . ' »"';
  21.       }
  22.       else {
  23.         $data = $attribute . '="' . check_plain($data) . '"';
  24.       }
  25.  
  26.     }
  27.     // Return the input.
  28.     return '<input ' . implode(' ', $attributes) . ' />';
  29.   }
  30.   else {
  31.     return '<input' . drupal_attributes($element['#attributes']) . ' />';
  32.   }
  33. }

Basically, we find the ID of the form element we want to add our html to then we build the input just like drupal_attributes would have. The only difference is that we append the $raquo; to the end of the 'value' attribute. The final result looks like this:


Comments