Add one or more custom submit handlers in Drupal

08 Feb

Add one or more custom submit handlers in Drupal

in Drupal, Drupal, Drupal Planet, Drupal Planet, forms

It is fairly trivial and useful to add one or more custom submit handlers in Drupal. in other words, when the user hits the submit button, you can write own handlers to interrupt the normal flow and perform custom actions on the form data. Like what you ask?

You might want to send out mails, preprocess data before submitting it, or store the data in different databases or format (files). There can be seneral usecases where you might want to interfere in the normal code execution flow.

What ever your usecase, here is the way to do it:

1. In the mymodule_form_alter() function (replace mymodule with your module's name), override the #submit property of the form your want to handle.

function mymodule_form_alter(&$form, &$form_state, $form_id){
switch($form_id){
    case 'some_form_id':
      // some code to handle the form. 
       $form['#submit'][] = 'mymodule_mysubmit_handler';
     break;
  }
}

switch($form_id){

    case 'some_form_id':
      // some code to handle the form. 
       $form['#submit'][] = 'mymodule_mysubmit_handler', 'mymodule_second_handler';
     break;
 }


Hopefully you get to use this powerful functionality.

Have fun

copyright 2012 10jumps Llc.

copyright 2012 10jumps LLC.