3

I'm trying to add a "cancel" button to my content type.

In hook_form_alter(), I'm using this code:

  if ($form_state->getFormObject()->getOperation() == 'default') { // On node add, make it clear "cancel" deletes any input
    // Do not show cancel button to people who have not completed their profile.
    if ($user->hasPermission('create MYTYPE content')) {
      $form['actions']['submit_cancel'] = array (
        '#type' => 'submit',
        '#weight' => 999,
        '#value' => t('Delete all input and return to previous page'),
        '#submit' => array('MYMODULE_userpageredirect_callback'),
        );
      $form['actions']['submit_cancel']['#attributes']['class'][] = 'btn-danger';
    }
  }

....

/**
 * Cancel changes and return to previous page
 * @param array $form
 * @param FormStateInterface $form_state
 */
function MYMODULE_userpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $route_name = 'user.page';
  $form_state->setRedirect($route_name);
}

This creates a cancel button that returns the user to the user page when they click cancel.

Problem

If a field is marked required, and the user has not input any text in the field, the browser prompts the user to input a value into the field before the cancel button will work.

1
  • In this case you might need to override the validation function in your hook_form_alter.
    – Ismini
    Nov 17, 2017 at 10:01

2 Answers 2

6

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' => [],
);
0

Module cancel_button provides that functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.