You are here

public function ProductVariation::toUrl in Commerce Core 8.2

Gets the URL object for the entity.

The entity must have an id already. Content entities usually get their IDs by saving them.

URI templates might be set in the links array in an annotation, for example:


links = {
  "canonical" = "/node/{node}",
  "edit-form" = "/node/{node}/edit",
  "version-history" = "/node/{node}/revisions"
}

or specified in a callback function set like:


uri_callback = "comment_uri",

If the path is not set in the links array, the uri_callback function is used for setting the path. If this does not exist and the link relationship type is canonical, the path is set using the default template: entity/entityType/id.

Parameters

string $rel: The link relationship type, for example: canonical or edit-form.

array $options: See \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute() for the available options.

Return value

\Drupal\Core\Url The URL object.

Throws

\Drupal\Core\Entity\EntityMalformedException

\Drupal\Core\Entity\Exception\UndefinedLinkTemplateException

Overrides EntityBase::toUrl

File

modules/product/src/Entity/ProductVariation.php, line 112

Class

ProductVariation
Defines the product variation entity class.

Namespace

Drupal\commerce_product\Entity

Code

public function toUrl($rel = 'canonical', array $options = []) {

  // Product variation URLs depend on the parent product.
  if (!$this
    ->getProductId()) {

    // RouteNotFoundException tells EntityBase::uriRelationships()
    // to skip this product variation's link relationships.
    throw new RouteNotFoundException();
  }

  // StringFormatter assumes 'revision' is always a valid link template.
  if (in_array($rel, [
    'canonical',
    'revision',
  ])) {
    $route_name = 'entity.commerce_product.canonical';
    $route_parameters = [
      'commerce_product' => $this
        ->getProductId(),
    ];
    $options += [
      'query' => [
        'v' => $this
          ->id(),
      ],
      'entity_type' => 'commerce_product',
      'entity' => $this
        ->getProduct(),
      // Display links by default based on the current language.
      'language' => $this
        ->language(),
    ];
    return new Url($route_name, $route_parameters, $options);
  }
  else {
    return parent::toUrl($rel, $options);
  }
}