ConfirmFormHelper.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Component\Utility\UrlHelper;
  4. use Drupal\Core\Url;
  5. use Symfony\Component\HttpFoundation\Request;
  6. /**
  7. * Provides common functionality to confirmation forms.
  8. */
  9. class ConfirmFormHelper {
  10. /**
  11. * Builds the cancel link for a confirmation form.
  12. *
  13. * @param \Drupal\Core\Form\ConfirmFormInterface $form
  14. * The confirmation form.
  15. * @param \Symfony\Component\HttpFoundation\Request $request
  16. * The current request.
  17. *
  18. * @return array
  19. * The link render array for the cancel form.
  20. */
  21. public static function buildCancelLink(ConfirmFormInterface $form, Request $request) {
  22. // Prepare cancel link.
  23. $query = $request->query;
  24. $url = NULL;
  25. // If a destination is specified, that serves as the cancel link.
  26. if ($query->has('destination')) {
  27. $options = UrlHelper::parse($query->get('destination'));
  28. // @todo Revisit this in https://www.drupal.org/node/2418219.
  29. try {
  30. $url = Url::fromUserInput('/' . ltrim($options['path'], '/'), $options);
  31. }
  32. catch (\InvalidArgumentException $e) {
  33. // Suppress the exception and fall back to the form's cancel url.
  34. }
  35. }
  36. // Check for a route-based cancel link.
  37. if (!$url) {
  38. $url = $form->getCancelUrl();
  39. }
  40. return [
  41. '#type' => 'link',
  42. '#title' => $form->getCancelText(),
  43. '#attributes' => ['class' => ['button']],
  44. '#url' => $url,
  45. '#cache' => [
  46. 'contexts' => [
  47. 'url.query_args:destination',
  48. ],
  49. ],
  50. ];
  51. }
  52. }