Skip to content
Snippets Groups Projects

Add availableLanguages field to nodes

4 files
+ 179
0
Compare changes
  • Side-by-side
  • Inline
Files
4
<?php
namespace Drupal\graphql_compose_available_translations\Plugin\GraphQL\DataProducer;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\node\NodeInterface;
/**
* Returns the translation strings.
*
* @DataProducer(
* id = "available_languages",
* name = @Translation("Load string translations"),
* description = @Translation("Loads a list of string translations."),
* produces = @ContextDefinition("any",
* label = @Translation("String translation connection")
* ),
* consumes = {
* "entity" = @ContextDefinition("entity:node",
* label = @Translation("Entity"),
* ),
* }
* )
*/
class AvailableLanguages extends DataProducerPluginBase {
/**
* Resolves the available languages.
*
* @param \Drupal\node\NodeInterface $node
* The current node.
*
* @return array
* An array of available languages.
*/
public function resolve(NodeInterface $node): array {
// Get the translation languages.
$languages = $node->getTranslationLanguages();
$translations = [];
foreach ($languages as $language) {
// Check if node has an ID.
if (!$node->id()) {
continue;
}
// Get the translated node for each language.
$translatedNode = $node->getTranslation($language->getId());
// Customize the logic to fetch available languages for the node.
$translations[] = [
'url' => (string) $translatedNode->toUrl()->toString(TRUE)->getGeneratedUrl(),
'language' => (string) $language->getId(),
];
}
return $translations;
}
}
Loading