ajax_dashboard-8.x-2.x-dev/src/Plugin/AJAXDashboardButton/Redirect.php

src/Plugin/AJAXDashboardButton/Redirect.php
<?php

namespace Drupal\ajax_dashboard\Plugin\AJAXDashboardButton;

use Drupal\ajax_dashboard\Plugin\AJAXDashboardButtonBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Url;

/**
 * Class Redirect.
 *
 * Set a button to redirect to another URL by setting a 'uri'
 * key for the button. You may also pass an 'options' key for
 * Url::fromUri().
 *
 * @package Drupal\ajax_dashboard\Plugin\AJAXDashboardButton
 *
 * @AJAXDashboardButton (
 *   id = "redirect",
 *   label = "Redirect"
 * )
 */
class Redirect extends AJAXDashboardButtonBase {

  /**
   * Get the redirect Url from button data, or log an error message.
   *
   * @param $button_data
   *   Array of button data for getting the URI.
   *
   * @return string|bool
   *   URL string, or FALSE.
   */
  public static function getUrlFromButtonData($button_data) {
    $uri_parts = parse_url($button_data['uri']);
    if ($uri_parts && !empty($uri_parts['scheme'])) {
      $options = !empty($button_data['options']) ? $button_data['options'] : [];
      $u = Url::fromUri($button_data['uri'], $options);
      $url = $u->toString();
      return $url;
    }
    $message_params = [
      '%uri' => $button_data['uri'],
      '%dashboard' => $button_data['dashboard_id']
    ];
    $message = t('Invalid redirect uri %uri on dashboard %dashboard', $message_params);
    \Drupal::logger('ajax_dashboard')->error($message);
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public static function getButtonDashboardContent(array $params = [], array $button_data = []) {
    if (!empty($button_data['uri'])) {
      $url = self::getUrlFromButtonData($button_data);
      if ($url) {
        $message = t('Redirecting to... %url', ['%url' => $url]);
        return ['#markup' => $message];
      }
    }
    return ['#markup' => ''];
  }

  /**
   * {@inheritdoc}
   */
  public static function AddAJAXResponseCommands(AjaxResponse $response = NULL, array $params = [], array $active_button = []) {
    if (!empty($active_button['button_data']['uri'])) {
      $url = self::getUrlFromButtonData($active_button['button_data']);
      if ($url) {
        $response->addCommand(new \Drupal\Core\Ajax\RedirectCommand($url));
      }
    }
    return $response;
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc