Related to my previous question -- I've got the button added to the form properly (thanks googletorp!), but now I'm having separate validation issues beyond just adding the button.
I have added a "Cancel" button to my custom content entity add/edit form, using hook_form_id_alter. When clicking this button I want it to leave the form completely and return to another admin-side page:
function mymodule_form_myform_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$form['actions']['cancel'] = array(
'#type' => 'button',
'#weight' => 10001,
'#submit' => array('cancel_submit'),
'#value' => t('Cancel'),
);
}
function cancel_submit() {
$response = new Symfony\Component\HttpFoundation\RedirectResponse(Url::fromUri('internal:/admin/mymodule/list', array('absolute' => true))->toString());
$response->send();
}
I can't get this to work because it's still trying to validate the form.
In my form code, my validation code will only execute if if ($form_state->getValue('op') == 'Save')
is true
, and this evaluates to false
for the Cancel button. However, while this is stopping my custom validation code from running, it isn't stopping built-in validation for fields that I defined as required in the Drupal interface. The cancel_submit
function doesn't seem to be doing anything, and clicking the Cancel button just loads the form again with a validation error on a required field.
I also tried adding '#limit_validation_errors' => array(),
to $form['actions']['cancel']
as recommended here, but this just refreshed the form without showing validation errors instead of redirecting where I want it to go, so I have no idea what this code is actually doing or if this is even applicable for Drupal 8.
I am not sure where to go from here.