drupaldrupal-7drupal-modulesdrupal-fapidrupal-forms

How to set a default submit button on a form with multiple submit form elements?


A question exactly like this was asked last year, but this question was for Drupal 6, I'm wondering if there has been a change for Drupal 7.

Can I make the second or later button in a Drupal form the default button?

In my form, I have about four submit button form elements. Three of the four have a specified submit function and the other one uses the default hook_form_submit() function to handle it's submission.

So this is what three buttons almost look like:

$form['reset'] = array(
   '#type' => 'submit',
   '#value' => t('Reset Values'),
   '#submit' => array('_phonebook_reset_config'),
);

This is what the main button looks like:

$form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Update'),
);

This is the order in which the buttons are created in the form: (Button_1, Button_2, Main_Button, Button_4).

Right now if I press enter on the form, Button_1 gets executed. I want the main button to be the default button, so that when the user press enter, that main button is submitted not Button_1.

In the post mentioned above, one of the answers was to use weight. I tried using weight, but all that did was change the way the button was ordered on the screen. Yes this did allow the Main_Button, to be submitted, but then I needed that button in its original location.


Solution

  • This can't be done with just HTML. (So there's nothing Form API can do) As there is no standard and no html properties to handle a default submit in a multiple submit form. You should use CSS but if you don't wanna restyle you can use jQuery. Good luck!

     //Not tested
      $("#target").keypress(function(event) {
        if ( event.which == 13 ) {
           event.preventDefault();
           $('correctSubmit').submit();
         }
      });