0

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)

1 Answer 1

0

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];
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.