- Create these folders: custom_module_change_this_name_here/src/Plugin/Block
- Add the file (see code below) in here: custom_module_change_this_name_here/src/Plugin/Block/LinkToOtherLanguage.php
<?php
/**
* @file
*/
namespace Drupal\custom_module_change_this_name_here\Plugin\Block;
use Drupal;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Block\BlockBase;
/**
* Provides a language switcher block
* @Block(
* id = "link_to_other_language",
* admin_label = @Translation("Custom Language switcher for wcag"),
* )
*/
class LinkToOtherLanguage extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$config = $this->getConfiguration();
$block['#id'] = $config['id'];
$block['#title'] = 'Custom Language switcher for wcag';
$block['content']['results']['#type'] = 'markup';
// Figure out the switch language.
$languages = Drupal::languageManager()->getLanguages();
$current_language = Drupal::languageManager()->getCurrentLanguage();
$switch_language = null;
foreach($languages as $language) {
if ($language->getId() !== $current_language->getId()) {
$switch_language = $language;
break;
}
}
// Get the path alias for the page in the switch language.
$current_path = Drupal::service('path.current')->getPath();
$result = Drupal::service('path.alias_manager')
->getAliasByPath($current_path, $switch_language->getId());
$aria_label_language = $switch_language->getName(); // Works with languages other than English/French.
if ($current_language->getId() == 'en') {
// Alternatively, $switch_language->getName();
$aria_label_language = 'Français';
}
if ($current_language->getId() == 'fr') {
$aria_label_language = 'English';
}
$block['content']['#markup'] = '<a class="nav-link language-link"'
. ' lang="' . $switch_language->getId() . '"'
. ' aria-label="' . $aria_label_language
. '" href="'
. '/' . $switch_language->getId() // Work around for alias bug to be fixed in 8.8.
. $result . '">' . $switch_language->getId() . '</a>';
// Return the link as a render-able array.
return $block;
}
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'access content');
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $formState) {
$config = $this->getConfiguration();
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $formState) {
$this->configuration['link_to_other_language'] =
$formState->getValue('link_to_other_language');
}
}