Créer un bloc sur mesure

 

  1. Créer des répertoires custom_module_change_this_name_here/src/Plugin/Block
  2. Créer ce fichier (voir code ci-dessous) dans ton module {mon_module}/src/Plugin/Block/LienVersDeuxiemeLangue.php

 

<?php
/**
 * @file
 */
namespace Drupal\mon_module\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 LienVersDeuxiemeLangue 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');
  }


}