Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle multiple submit buttons in Drupal form API

Tags:

drupal

I have 2 submit buttons and want to perform different actions for each submit button . Here I want to set the form fields which can be done only in form_alter(). Can anyone suggest how to check for multiple submit buttons in the form_alter() function?

I have used

function myform_form_submit($formID, &$form_state) { if($form_state['clicked_button']['#value'] == $form_state['values']['submit_one'])    //if button 1      is clicked      $form_state['redirect'] = 'mypath/page_one';   //redirect to whatever page you want  else if($form_state['clicked_button']['#value'] == $form_state['values']['submit_two'])  /if button      2 is clicked     $form_state['redirect'] = 'mypath/page_two';  } 

but this does not work

like image 418
user550265 Avatar asked Dec 21 '10 17:12

user550265


People also ask

Can you have multiple submit buttons in a form?

yes, multiple submit buttons can include in the html form.

How can use multiple submit button in PHP?

Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked. Show activity on this post.

How many methods are required minimum to create a form in Drupal?

Form API workflow is dependent on four main methods i.e. getFormId, buildForm, validateForm, and submitForm. While requesting any form, we can define it using a nested array “$form” which is easily renderable. We can use different abstract classes to provide a base class to form.


1 Answers

The best thing to do if you have two submit buttons on a form and want them to do different things, is to create a different submit function for each button, and connect them up. One of the nice things about the FormAPI is that it automatically links the form with the submit handler for you, but if you have two submit buttons you want to go somewhere new.

So your form code is likely to contain:

$form['submit_one'] = array(   '#type' => 'submit',   '#value' => t('Submit One'),   '#submit' => array('my_module_form_submit_one'), ); $form['submit_two'] = array(   '#type' => 'submit',   '#value' => t('Submit Two'),   '#submit' => array('my_module_form_submit_two'), ); 

But I don't know what you mean by form_alter() - there's no reason to use a form alter of any sort.

Edit: As came up in the comments - if you need different validation functions for the two buttons, you can also include '#validate' => array('my module_form_validate_one') and '#validate' => array('my module_form_validate_two') in the respective button arrays. But it's not required, and if the standard form validation function works fine then go with that.

like image 72
John Fiala Avatar answered Oct 04 '22 15:10

John Fiala