Route access checks can now account for a specified language for any language type supported by the language manager.
This can be done via the following:
Create a Drupal\Core\Url object from a route and set the language option.
$language= \Drupal::service('language_manager')->getLanguage($langcode);
$url = Drupal\Core\Url::fromRoute('route_name', [], ['language' => $language]); //Also can use $url->setOption('language', $language) if not passed in initially.
$access = $url->access();
The language option was previously documented for Url objects as being used for in path processing in string URL generation, and it has been extended for use in access checks. Setting the language option will do the following:
- Makes the
EntityConverterandEntityRevisionParamConverterupcast entity parameters to entity translations (if they exist) in the specified language - Makes Language objects available as arguments to any route access callback. If the route access callback method has arguments that are typed to
Drupal\Core\Language\LanguageInterfacewith names that match a language type, such aslanguage_interfaceorlanguage_content, then those arguments will have the value of the specified language. Note that the argument names can be snake- or camel-cased
Example
my_module.routing.yml
my_route:
name: my_module.my_route
path: /my-path
requirements:
_custom_access: Drupal\my_module\Access\MyRouteAccess::access
MyRouteAccess.php:
public static function access(?LanguageInterface $languageContent = NULL, ?LanguageInterface $language_interface = NULL): AccessResultInterface {
...
}
Note that setting the language option in the Url will set the same language value for all types. If the access callback needs to account for different language per type, route parameters with the language codes can be set. Note that the parameter names are the language types with an '_' suffix, in order to avoid collisions with other parameters or defaults possibly defined on any route.
$url = Drupal\Core\Url::fromRoute('route_name', [
'language_content_' => $langcode1,
'language_interface_' => $langcode2,
]);
$access = $url->access();
In the event that no language is specified by the Url or Route object, the language passed to the access callbacks will be the current negotiated language for the matching language type.
Deprecation
To support this change, the $languageManager argument has been added to the AccessManager constructor. Not passing this argument is deprecated and it will be required in Drupal 12.