1

I have several custom fields on craftcms (cp/settings/fields), and some of them are dropdowns.

I'm trying to get this custom fields data (for example the dropdown options) on graphql, because we are using this data in another system out of CraftCMS, but I really do not have any idea on how to do it.

Thanks.

1 Answer 1

1

Here's an example of how you can retrieve the options for a dropdown field:

use craft\gql\base\FieldType;
use GraphQL\Type\Definition\Type;

class DropdownField extends FieldType
{
    public static function getTypeName(): string
    {
        return 'DropdownField';
    }

    public static function getFieldDefinition(): array
    {
        return [
            'name' => 'options',
            'type' => Type::listOf(Type::string()),
            'args' => [
                'fieldHandle' => Type::nonNull(Type::string()),
            ],
            'resolve' => function ($root, $args) {
                $fieldHandle = $args['fieldHandle'];
                $options = [];
                $field = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
                if ($field) {
                    $options = $field->settings['options'];
                }
                return $options;
            },
        ];
    }
}

You can register this field by adding it to your module's init method:

use craft\gql\base\Type;

class MyModule extends \yii\base\Module
{
    public function init()
    {
        parent::init();

        // Register GraphQL type for custom fields
        Event::on(
            Type::class,
            Type::EVENT_DEFINE_TYPES,
            function (DefineGqlTypesEvent $event) {
                $event->types[] = DropdownField::class;
            }
        );
    }
}

With this code in place, you can now query the options for a dropdown field using GraphQL, for example:

{
  entry(id: 123) {
    ... on MyEntryType {
      myDropdownField(options: {fieldHandle: "myDropdownField"}) {
        options
      }
    }
  }
}

This would return the options for the myDropdownField custom field on the MyEntryType entry with ID 123.

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.