You are here

function hook_cancel_button_destination_alter in Entity Form Cancel Button 8

Allow other modules to alter the cancel button destination.

Parameters

\Drupal\Core\Url $destination: The destination Url object to alter.

array $context: An array of contextual data about the form where the cancel button appears. Keys include:

  • 'settings': The module's configured default (fallback) destination settings for the cancel button.
  • 'request': The Symfony Request object for the form where the button appears.
  • 'route_match': The RouteMatch object for the form where the button appears.
  • 'entity_type': The entity type definition for the entity on the form where the button appears.
  • 'form_state': The FormState object.
1 invocation of hook_cancel_button_destination_alter()
cancel_button_form_alter in ./cancel_button.module
Implements hook_form_alter().

File

./cancel_button.api.php, line 34
Hooks provided by the Cancel Button module.

Code

function hook_cancel_button_destination_alter(Url &$destination, array $context) {
  if ($context['entity_type']
    ->id() === 'node') {

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $context['form_state']
      ->getFormObject()
      ->getEntity();

    // If this is node 1, set the cancel button destination to the collection
    // URL rather than to the canonical URL.
    if ($entity
      ->id() == 1) {
      try {
        $destination = $entity
          ->toUrl('collection');
      } catch (EntityMalformedException $exception) {

        // If the entity does not have a collection URL, abort without changing
        // destination.
        return;
      }
    }
  }
}