Add cancel button in your Drupal form

You can add the Cancel button or Cancel link in your Drupal form so you can cancel the form and go back previous page.

Code:-

<?php
$form['submit'] = array(#type’ => ’submit’,
#value’ => t(’Submit’),
);
$form['cancel'] = array(#type’ => ‘markup’,
#value’ => l(t(’Cancel’), ‘category’),
);
?>

This code add a “Cancel” link after “Submit” button.

,


  1. #1 by sim6 - January 27th, 2010 at 18:56

    Hi,

    That code don’t show a button, show a link.

    The next code show a button:

    // hook_form()
    function myform_form($form_state, $value) {
      $form['cancel'] = array(
    	'#type' => 'button',
    	'#attributes' => array('onClick' => 'location.replace("'. referer_uri() .'"); return false;'),
    	'#value' => t('Cancel'),
      );
    }
    

    Enjoy it!

  2. #2 by Jack - February 8th, 2010 at 15:51

    @ sim6
    Thanks! its working fine

  3. #3 by Eric Davis - August 5th, 2011 at 03:58

    I work in Ruby on Rails and the standard way Cancels are done are using links. This is because most cancel links are considered safe since they are GET requests and don’t affect the server state (e.g. they shouldn’t delete anything). Buttons, like what sim6 posted, typically send POST requests which are sometimes handled differently.

    Also sim6′s code requires JavaScript to work and could be subject to referer hacking. A better version would be to use ‘history.back()’ in the onclick or remove the JavaScript entirely and rely on the server to send the user back.

    W3C has a good document on GET vs POST requests, it’s worth a read: http://www.w3.org/2001/tag/doc/whenToUseGet.html#safe

(will not be published)

 


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.