You are here

public function EntityUrlLanguageTrait::toUrl in Open Social 8.8

Same name and namespace in other branches
  1. 8.9 modules/social_features/social_core/src/EntityUrlLanguageTrait.php \Drupal\social_core\EntityUrlLanguageTrait::toUrl()
  2. 10.3.x modules/social_features/social_core/src/EntityUrlLanguageTrait.php \Drupal\social_core\EntityUrlLanguageTrait::toUrl()
  3. 10.0.x modules/social_features/social_core/src/EntityUrlLanguageTrait.php \Drupal\social_core\EntityUrlLanguageTrait::toUrl()
  4. 10.1.x modules/social_features/social_core/src/EntityUrlLanguageTrait.php \Drupal\social_core\EntityUrlLanguageTrait::toUrl()
  5. 10.2.x modules/social_features/social_core/src/EntityUrlLanguageTrait.php \Drupal\social_core\EntityUrlLanguageTrait::toUrl()

File

modules/social_features/social_core/src/EntityUrlLanguageTrait.php, line 27

Class

EntityUrlLanguageTrait
Provides a trait to fix the URL generation for single-language entities.

Namespace

Drupal\social_core

Code

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

  // If a language was requested explicitly then it's not overwritten.
  // e.g. this happens on content translations overview pages for links to the
  // specific translations.
  if (isset($options['language'])) {
    return $url;
  }
  $url_options = $url
    ->getOptions();

  // Only override the language if the parent `toUrl` method specified a
  // language. This avoids accidentally setting a language for a page that is
  // not tied to the entity's language.
  if (isset($url_options['language'])) {

    // Override the language to keep the user in the current content language.
    // By default Drupal sets the link language to the Entity's language which
    // would cause the content language for the current user to change, this
    // is undesired. Setting the language to the current content user relies
    // on the fact that Drupal displays the default language translation for
    // the entity when no translation is available but properly adjusts links.
    $url_options['language'] = $this
      ->languageManager()
      ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
    $url
      ->setOptions($url_options);
  }
  return $url;
}