Add cancel button to (defined) forms

Public

Configuration example for the variable 'mymodule_add_cancel' when this is set in the settings.php.

</> CopyGet raw version
php
  1. /**
  2.  * Cancel button added to the following forms
  3.  */
  4. $conf['mymodule_add_cancel'] = array(
  5. 'event_node_form' => TRUE,
  6. 'committee_node_form' => TRUE,
  7. 'profile_node_form' => TRUE,
  8. 'user_profile_form' => TRUE,
  9. 'og_ui_add_users' => TRUE,
  10. 'field_collection_item_form' => TRUE,
  11. 'taxonomy_form_term' => TRUE,
  12. );

This code adds a cancel button to defined form id's.

</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_form_alter().
  3.  */
  4. function mymodule_form_alter(&$form, &$form_state, $form_id) {
  5.  
  6. // Add an additional cancel button to defined forms
  7. $cancel = variable_get('mymodule_add_cancel', array());
  8. if(isset($cancel[$form_id])) {
  9.  
  10. // Use destination parameter when set
  11. if (isset($_GET['destination'])) {
  12. $form['actions']['cancel'] = array(
  13. '#type' => 'submit',
  14. '#value' => t('Cancel'),
  15. '#submit' => array('mymodule_cancel_button_callback'),
  16. '#limit_validation_errors' => array(),
  17. '#weight' => 100,
  18. );
  19. }
  20. // Use javascript history.go(-1) when destination is not set
  21. else {
  22. $form['actions']['cancel'] = array(
  23. '#type' => 'button',
  24. '#value' => t('Cancel'),
  25. '#attributes' => array('onClick' => 'history.go(-1); return true;'),
  26. '#post_render' => array('mymodule_cancel_button_change_type'),
  27. '#weight' => 100,
  28. );
  29. }
  30. }
  31. }
  32.  
  33. /**
  34.  * Cancel button callback when a destination parameter was set.
  35.  */
  36. function mymodule_cancel_button_callback($form, &$form_state) {
  37. drupal_goto();
  38. }
  39.  
  40. /**
  41.  * Changed the default html button type from 'submit' to 'button'
  42.  */
  43. function mymodule_cancel_button_change_type($markup, $element) {
  44. $markup = str_replace('type="submit', 'type="button', $markup);
  45. return $markup;
  46. }