Language blocks always show all languages but you only want to show the ones which content translations exist for.
<?php
namespace Drupal\content_translation_language_block\Plugin\Block;
use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\language\Plugin\Block\LanguageBlock;
use Drupal\language\Plugin\Derivative\LanguageBlock as LanguageBlockDeriver;
/**
* Provides a 'Content translation language switcher' block.
*/
#[Block(
id: "content_translation_language_block",
admin_label: new TranslatableMarkup("Language switcher"),
category: new TranslatableMarkup("Content translation"),
context_definitions: [
"entity" => new ContextDefinition("entity",
label: new TranslatableMarkup("Entity"),
required: TRUE
),
],
deriver: LanguageBlockDeriver::class
)]
class ContentTranslationLanguageBlock extends LanguageBlock implements ContainerFactoryPluginInterface {
/**
* {@inheritdoc}
*/
public function build() {
$build = parent::build();
if ($entity = $this->getContextValue('entity')) {
foreach ($build['#links'] as $langcode => $link) {
if (!$entity->hasTranslation($langcode)) {
unset($build['#links'][$langcode]);
}
}
if (count($build['#links']) < 2) {
unset($build['#links']);
}
}
return $build;
}
}
Issue:
Language blocks always show all languages but you only want to show the ones which content translations exist for.
Prerequisites:
- You need to be in the context of a translatable content entity.
- We make use of the Entity Route Context module which needs to be installed.
Solution:
Extend the Core plugin using the provided copy-and-paste snippet.
The snippet checks whether the current entity has translations. If any are found, the language options are reduced to those for which a translation exists.