How to create a "go back" or "cancel" button on the node add form?
Adding '#limit_validation_errors' will help override validation,
$form['actions']['submit_cancel'] = array (
'#type' => 'submit',
'#weight' => 999,
'#value' => t('Delete all input and return to previous page'),
'#submit' => array('MYMODULE_userpageredirect_callback'),
'#limit_validation_errors' => [],
);
this will cause the form to be rebuild
also you need to add a callback method
For drupal 10, you can install a module 'Cancel Button', which will be good for any form already developed
The Cancel Button module allows site administrators to enable a cancel button on entity forms.
For Drupal7 we will need to be smart
-
lets get the current location:
$referer_path = $_SERVER['HTTP_REFERER'];
-
let set the cancel form element api
$form['actions']['cancel'] = array(
'#type' => 'button',
'#value' => t('Cancel'),
'#attributes' => [
'onClick' => 'window.location.replace("'.$referer_path.'"); return false;'
],
);
the page will be refreshed