Score:0

Fetch select label via GraphQL

cn flag

My nodes have an "articleType" property, which is a select field with ~10 options ("article|Article", "training|Web based training" etc).

Fetching the property via GraphQL (8.x-3.1) works, but this gives me the key of the selected option (training):

    [...]
    results {
      entityLabel
      ...on NodeArticle {
        fieldArticleType
      }
    }
    [...]

I would like to retrieve the label of the selected option (Web based training). How can I do that?

(Related, but without GraphQL: How to access a selected label instead of value)

Score:0
cn flag

I solved it by adding a new GraphQL field:

<?php

namespace Drupal\mymodule\Plugin\GraphQL\Fields;

use Drupal\graphql\GraphQL\Execution\ResolveContext;
use Drupal\graphql\Plugin\GraphQL\Fields\FieldPluginBase;
use Drupal\node\Entity\Node;
use GraphQL\Type\Definition\ResolveInfo;

/**
 * Returns the label for the "article type" field
 *
 * Example: "Themendossier" label instead of "dossier" key.
 *
 * @GraphQLField(
 *   id = "article_type_label",
 *   type = "String",
 *   name = "articleTypeLabel",
 *   nullable = true,
 *   multi = false,
 *   parents = {"NodeArticle"}
 * )
 */
class ArticleTypeLabel extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function resolveValues(Node $value, array $args, ResolveContext $context, ResolveInfo $info) {
    $options = $value->field_article_type->getFieldDefinition()->getFieldStorageDefinition()
        ->getSetting('allowed_values');

    yield $options[$value->field_article_type->value];
  }
}

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.