ConfirmFormHelper.php 1.53 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Form;

5
use Drupal\Component\Utility\UrlHelper;
6
use Drupal\Core\Url;
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
use Symfony\Component\HttpFoundation\Request;

/**
 * Provides common functionality to confirmation forms.
 */
class ConfirmFormHelper {

  /**
   * Builds the cancel link for a confirmation form.
   *
   * @param \Drupal\Core\Form\ConfirmFormInterface $form
   *   The confirmation form.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return array
   *   The link render array for the cancel form.
   */
  public static function buildCancelLink(ConfirmFormInterface $form, Request $request) {
    // Prepare cancel link.
    $query = $request->query;
28
    $url = NULL;
29 30
    // If a destination is specified, that serves as the cancel link.
    if ($query->has('destination')) {
31
      $options = UrlHelper::parse($query->get('destination'));
32
      // @todo Revisit this in https://www.drupal.org/node/2418219.
33 34 35 36 37 38
      try {
        $url = Url::fromUserInput('/' . ltrim($options['path'], '/'), $options);
      }
      catch (\InvalidArgumentException $e) {
        // Suppress the exception and fall back to the form's cancel url.
      }
39 40
    }
    // Check for a route-based cancel link.
41
    if (!$url) {
42
      $url = $form->getCancelUrl();
43 44
    }

45 46 47
    return [
      '#type' => 'link',
      '#title' => $form->getCancelText(),
48
      '#attributes' => ['class' => ['button']],
49
      '#url' => $url,
50 51 52 53 54
      '#cache' => [
        'contexts' => [
          'url.query_args:destination',
        ],
      ],
55
    ];
56 57 58
  }

}