In Drupal 7 form API - How do I create an input of type "button" (not "submit")?

28,334

Solution 1

You may want to check out this issue for some background and then consider this workaround. You might also be able to use #markup to insert it manually.

Solution 2

You can use:

"#executes_submit_callback" => FALSE

To disable the "submit" step.

If you only want to disable the "validate" step, use:

"#limit_validation_errors" => array()

Solution 3

In Drupal 7 this can be accomplished by adding:

'#attributes' => array('onclick' => 'return (false);'),

to your button definition. For example:

$form['my_form'] = array(
 '#type' => 'button',
 '#attributes' => array('onclick' => 'return (false);'),
 '#value' => t('My Button'),
 '#prefix' => t('<div class="myButton">'),
 '#suffix' => t('</div>')
);

This worked for my application.

Reference: https://www.drupal.org/node/283065 under Disabling and Overriding Buttons

Solution 4

A very simple side-step is the following in your form

$form['your-form-element'] = array(
    '#type' => 'button',
    '#name' => 'any-name',
    '#value' => t('Button Text'),
);

And in your form's template:

print str_replace('type="submit"', 'type="button"', drupal_render($form['your-form-element']));

Solution 5

Add the following function in your template's template.php file.

function templatename_button($variables) {
  $element = $variables['element'];
  $type = strtolower($element['#button_type']);
  switch($type){
    case 'submit':
    case 'reset':
    case 'button':
      break;
    default:
      $type = 'submit';
      break;
  }
  $element['#attributes']['type'] = $type;

  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

and in your form

  $form['mybutton'] = array(
    '#type'  => 'button',
    '#value' =>  t('mytext'),
    '#button_type' => 'button',
  );
Share:
28,334
Doron
Author by

Doron

SMILEUPPS-9B58F9CF17

Updated on July 09, 2022

Comments

  • Doron
    Doron almost 2 years

    I am trying to have a button which is not a "submit" type of button, but rather a normal "button" type, using the forms api of drupal 7, but I can't seem to get it.

    I've tried many things, like setting #type to 'button', setting #button_type to 'button' but no matter what I do, drupal always creates a button of type "submit".

  • Professor Falken
    Professor Falken about 12 years
    This was such a simple and effective solution!
  • badzilla
    badzilla over 11 years
    To add to my earlier example - that is the Drupal 6 version. In Drupal 7, change the drupal_render to render