I have a view
$view = \Drupal\views\Views::getView($view_id);
How to determine if it has been translated into other available languages and which ones
I have been fighting with this lately, and can answer part of the question. If you have the $viewId
and $displayId
, then the following seems to indicate whether a translation of the view label, title, and/or view menu entry exists in any language (but does not indicate the language):
$viewConfig = \Drupal::configFactory()->get("views.view.$viewId");
$hasTranslation = $viewConfig && ($viewConfig->hasOverrides('label') ||
$viewConfig->hasOverrides("display.$displayId.display_options.menu.title") ||
$viewConfig->hasOverrides('display.default.display_options.title'));
Since we need to manually add path aliases for translated views, a set alias does provide an indirect opportunity to see if a translation exists.
You could check with ->lookupBySystemPath($path, $langcode)
to see if a view has a path alias for a given language.
// Set route match.
$routeMatch = \Drupal::routeMatch();
// Get route object.
$routeObject = $routeMatch->getRouteObject();
// Check if route object.
if ($routeObject) {
// Get view id and display id from route.
$view_id = $routeObject->getDefault('view_id');
$display_id = $routeObject->getDefault('display_id');
// Check if view.
if (!empty($view_id) && !empty($display_id)) {
// Get current path.
$currentPath = \Drupal::service('path.current')->getPath();
// Get path alias repository.
$pathAliasRepository = \Drupal::service('path_alias.repository');
// Check if system path has Spanish alias.
if ($pathAliasRepository->lookupBySystemPath($currentPath, 'es')) {
// Do stuff...
}
}
}