2

I've created an add/edit form for a custom entity type, which extends Drupal\Core\Entity\ContentEntityForm. By default this form always comes with a "Save" button, and a "Delete" button if editing. I've been asked to add a "Cancel" button as well, but can't figure out how this is supposed to be done in Drupal.

I've seen plenty of answers about using hook_form_alter(), but nothing that is really working. My current solution is to add

$form['cancel'] = array(
    '#type' => 'submit',
    '#weight' => 10001,
    '#submit' => array('cancel_submit'),
    '#value' => t('Cancel'),
);

to the form's form() function, where cancel_submit() is a custom function, but that renders like this which looks awful.

How can I get the two buttons to be in line with each other? Is there a way to properly add a button to the form actions?

1 Answer 1

5

This is relatively simple when you define the form class yourself and one of the reasons Drupal 8 has gone all out on OOP. What you need to do is to extend the form class and implement the ::actions method. This would look like this:

class CustomEntityForm extends ContentEntityForm {
  ...

  protected function actions(array $form, FormStateInterface $form_state) {
    $actions =  parent::actions($form, $form_state);
    $actions['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelSubmit'],
    ];
    return $actions;
  }

  public function cancelSubmit($form, FormStateInterface $form_state) {
    // Du custom submit validation
  }

}

You could also achieve this with normal form alter, but would need to place the submit button inside the actions element, which is usually called actions, fx

$form['actions']['cancel'] = array(
  '#type' => 'submit',
  '#weight' => 10001,
  '#submit' => array('cancel_submit'),
  '#value' => t('Cancel'),
);
2
  • Thanks for the answer. I'm attempting your first method, but it's crashing my site with this message: "The website encountered an unexpected error. Please try again later. Recoverable fatal error: Argument 1 passed to Drupal\Core\Render\Element::children() must be of the type array, null given, called in {directory}\core\lib\Drupal\Core\Entity\EntityForm.php on line 206 and defined in Drupal\Core\Render\Element::children() (line 71 of core\lib\Drupal\Core\Render\Element.php)."
    – saramm1
    Oct 11, 2016 at 14:34
  • @saramm1 I updated the code in the first method, you should note that code is mostly example code, not meant for copy/paste without edits
    – googletorp
    Oct 11, 2016 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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