ViewExecutable::getUrl

public ViewExecutable::getUrl($args = NULL, $display_id = NULL)

Gets the URL for the current view.

This URL will be adjusted for arguments.

Parameters

array $args: (optional) Passed in arguments.

string $display_id: (optional) Specify the display ID to link to, fallback to the current ID.

Return value

\Drupal\Core\Url The URL of the current view.

Throws

\InvalidArgumentException Thrown when the current view doesn't have a route available.

File

core/modules/views/src/ViewExecutable.php, line 1919

Class

ViewExecutable
Represents a view as a whole.

Namespace

Drupal\views

Code

public function getUrl($args = NULL, $display_id = NULL) {
  if (!empty($this->override_url)) {
    return $this->override_url;
  }

  $display_handler = $this->displayHandlers->get($display_id ? : $this->current_display)->getRoutedDisplay();
  if (!$display_handler instanceof DisplayRouterInterface) {
    throw new \InvalidArgumentException('You cannot create a URL to a display without routes.');
  }

  if (!isset($args)) {
    $args = $this->args;

    // Exclude arguments that were computed, not passed on the URL.
    $position = 0;
    if (!empty($this->argument)) {
      foreach ($this->argument as $argument) {
        if (!empty($argument->is_default) && !empty($argument->options['default_argument_skip_url'])) {
          unset($args[$position]);
        }
        $position++;
      }
    }
  }

  $path = $this->getPath();

  // Don't bother working if there's nothing to do:
  if (empty($path) || (empty($args) && strpos($path, '%') === FALSE)) {
    return $display_handler->getUrlInfo();
  }

  $argument_keys = isset($this->argument) ? array_keys($this->argument) : array();
  $id = current($argument_keys);

  /** @var \Drupal\Core\Url $url */
  $url = $display_handler->getUrlInfo();
  $route = $this->routeProvider->getRouteByName($url->getRouteName());

  $variables = $route->compile()->getVariables();
  $parameters = $url->getRouteParameters();

  foreach ($variables as $variable_name) {
    if (empty($args)) {
      // Try to never put % in a URL; use the wildcard instead.
      if ($id && !empty($this->argument[$id]->options['exception']['value'])) {
        $parameters[$variable_name] = $this->argument[$id]->options['exception']['value'];
      }
      else {
        // Provide some fallback in case no exception value could be found.
        $parameters[$variable_name] = '*';
      }
    }
    else {
      $parameters[$variable_name] = array_shift($args);
    }

    if ($id) {
      $id = next($argument_keys);
    }
  }

  $url->setRouteParameters($parameters);
  return $url;
}
doc_Drupal
2016-10-29 09:54:22
Comments
Leave a Comment

Please login to continue.