Drupal Quick Tip #2: Using Images as Submit Buttons (5.x)

Posted by brenda

This is a pretty simple task but one I seem to end up doing over and over again for whatever project I'm working on at the time. I've done it a number of ways, from simply using CSS and dealing with multiple cross-browser issues, and probably quite a few alterations of this technique.

EDIT: chx pointed out I was doing this all wrong and wouldn't work when dealing with multiple submit buttons. Looking at the views_ui.module, there's a proper way to do this. See below:

In our custom module we're going to need a couple functions. First, we need to use hook_elements to define our new image element.

<?php
function siteconfig_elements() {
 
$type['image_button'] = array(
   
'#input' => TRUE,
   
'#button_type' => 'submit',
  );
  return
$type;
}
?>

Next, we need to theme our new type of element, which is called image_button above.

<?php
function theme_image_button($element) {
  return
'<input type="image" class="form-'. $element['#button_type'] .'" name="'. $element['#name'] .'" value="' . check_plain($element['#default_value']) .'" '. drupal_attributes($element['#attributes']) . ' src="' . $element ['#image'] . '" alt="' . $element['#title'] . '" title="' . $element['#title'] . "\" />\n";
}
?>

This is a very similar to Drupal's core theme_button function.

This function is needed to ensure the default_value doesn't get moved to #value. This should solve the issue with multiple submit buttons some browsers have.

<?php
function image_button_value() {                                                                       
// null value to guarantee default_value doesn't get moved to #value                                                                                                                                     } 
?>

Next, we need to use our trusty old hook_form_alter for the submit button of our choice.

<?php
function siteconfig_form_alter($form_id, &$form) {
  if (
$form_id == 'myformid') {
   
$form['submit'] = array(
     
'#type' => 'image_button',
     
'#image' => base_path() . path_to_theme() .'/images/search-btn.gif',
     
'#title' => t('Search'),
     
'#default_value' => t('Search'),
    );
  }
}
?>

Voila! Thanks chx and merlinofchaos. ;)

Tags: