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.