Magento – add custom attribute to customer in graphql magento 2

customergraphqlmagento2.3

my custom module

schema.graphql

input CustomerInput {
    sample_attribute: String @doc(description: "new attribute")
}

but not adding this attribute in customer mutation

magento 2 graphql

I created a custom attribute in Magento backend for Customers

sample_attribute

I tried this answer Answer

how I can solve this??

Best Answer

I guess that you are trying to return a new attribute (a custom one) via customer GQL query. The below answer is based on that.

Below is the sample code of adding a custom attribute to Customer GraphQl query.

Module NameSpace : Kcc Module Name : CustomerGraphQl

app/code/Kcc/CustomerGraphQl/etc/schema.graphqls

type Customer {
    sample_attribute: String @resolver(class: "Kcc\\CustomerGraphQl\\Model\\Resolver\\Sample")
}

The resolver class app/code/Kcc/CustomerGraphQl/Model/Resolver/Sample.php

<?php

declare(strict_types=1);

namespace Kcc\CustomerGraphQl\Model\Resolver;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory as BestSellersCollectionFactory;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

class Sample implements ResolverInterface
{
    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        // Return the value of sample_attribute here.
        return 'My sample attr value';
    }
}

When you run the customer query, it should return the new attribute if requested. enter image description here

Related Topic