Sometimes we need to add a Cancel button to some of the forms we are working with in Drupal. Maybe you want the user to be redirected to another page if he presses cancel or you want to perform some other action.
This can be a very easy task if you know how to do it. But if you don’t know how to do it, i will show you in this article.
So first we need to alter the form and add the button to the form array:
$form[‘cancel’] = array(
‘#type’ => ‘button’,
‘#value’ => t(‘Cancel’),
‘#weight’ => 20,
‘#executes_submit_callback’ => TRUE,
‘#submit’ => array(‘mymodule_form_cancel’),
Now let’s explain. The cancel button definition has to be somewhat similar to the submit button definition but with a few differences. For example the ‘#executes_submit_callback‘ property will result in the form being submitted when the user click on the Cancel button (By the way this property defaults to false for button type and to true for submit type form elements.). But with a difference. Now we can tell with the ‘#submit‘ property what function to be executed on the submit.
So you define another function in your module (the one specified in the submit property)
This function will be executed when the user clicked on the Cancel button. Isn’t this simple ?