For some unique customization, we need to create customer extension attribute to fulfil client requirements in magento2.

In this blog, I created extension attribute with different datatype.

is_happy_customer boolean
happy_message string
happy_number int
happy_list array
happy_object object

First create file etc/extension_attributes.xml

XML
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Customer\Api\Data\CustomerInterface">
        <attribute code="is_happy_customer" type="boolean"/>
        <attribute code="happy_message" type="string"/>
        <attribute code="happy_number" type="int"/>
        <attribute code="happy_list" type="array"/>
        <attribute code="happy_object" type="MageDad\Module\Api\Data\HappyObjectInterface[]"/>
    </extension_attributes>
</config>


Now we need to create interface and model for HappyObject
Create interface at app/code/MageDad/Module/Api/Data/HappyObjectInterface.php

PHP
<?php
declare(strict_types=1);

namespace MageDad\Module\Api\Data;

use Magento\Framework\Api\ExtensibleDataInterface;

interface HappyObjectInterface extends ExtensibleDataInterface
{
    public const ENTITY_ID = 'entity_id';
    public const HAPPY_MESSAGE = 'happy_message';

    /**
     * @return int|null
     */
    public function getId(): ?int;

    /**
     * @param int|null $entityId
     * null required for create queries @see \Magento\Framework\Model\ResourceModel\Db\AbstractDb::isObjectNotNew
     * @return $this
     */
    public function setId(?int $entityId): static;

    /**
     * @return string
     */
    public function getHappyMessage(): string;

    /**
     * @param string $country
     * @return $this
     */
    public function setHappyMessage(string $happyMessage): static;

}


Create model at app/code/MageDad/Module/Model/HappyObject.php

PHP
<?php
declare(strict_types=1);

namespace MageDad\Module\Model;

use Magento\Framework\Model\AbstractModel;
use MageDad\Module\Api\Data\HappyObjectInterface;

class HappyObject extends AbstractModel implements HappyObjectInterface
{
    /**
     * @inheritDoc
     */
    public function getId(): ?int
    {
        return (int)$this->getData(HappyObjectInterface::ENTITY_ID);
    }

    /**
     * @inheritDoc
     */
    public function setId($entityId): static
    {
        return $this->setData(HappyObjectInterface::ENTITY_ID, $entityId);
    }

    /**
     * @inheritDoc
     */
    public function getHappyMessage(): string
    {
        return (string)$this->getData(HappyObjectInterface::HAPPY_MESSAGE);
    }

    /**
     * @inheritDoc
     */
    public function setHappyMessage(string $happyMessage): static
    {
        return $this->setData(HappyObjectInterface::HAPPY_MESSAGE, $happyMessage);
    }
}


Now we create plugin for bind attribute value of extension attribute.
Create di.xml at app/code/MageDad/Module/etc/di.xml

XML
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Api\CustomerRepositoryInterface">
        <plugin name="magedad_module_happy_customer"
            type="MageDad\Module\Plugin\CustomerPlugin"/>
    </type>
    <preference for="MageDad\Module\Api\Data\HappyObjectInterface" type="MageDad\Module\Model\HappyObject" />
</config>


Create plugin at app/code/MageDad/Module/Plugin/CustomerPlugin.php

PHP
<?php
declare(strict_types=1);

namespace MageDad\Module\Plugin;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerExtensionInterface;
use Magento\Framework\Api\ExtensionAttributesFactory;
use MageDad\Module\Model\HappyObject;

class CustomerPlugin
{
    public function __construct(
        private ExtensionAttributesFactory $extensionFactory,
        private HappyObject $happyObject,
    ) {
    }

	public function afterGetById(CustomerRepositoryInterface $subject, CustomerInterface $customer)
    {
        $extensionAttributes = $customer->getExtensionAttributes();
        if ($extensionAttributes === null) {
            /** @var CustomerExtensionInterface $extensionAttributes */
            $extensionAttributes = $this->extensionFactory->create(CustomerInterface::class);
            $customer->setExtensionAttributes($extensionAttributes);
        }

        if ($extensionAttributes?->getIsHappyCustomer() === null) {
            $extensionAttributes->setIsHappyCustomer(true);
        }

        if ($extensionAttributes?->getHappyMessage() === null) {
            $extensionAttributes->setHappyMessage('I am so happy');
        }

        if ($extensionAttributes?->getHappyNumber() === null) {
            $extensionAttributes->setHappyNumber(1);
        }

        if ($extensionAttributes?->getHappyList() === null) {
            $extensionAttributes->setHappyList([
              "I",
              "Am"
              "Happy"
              ]);
        }

        if ($extensionAttributes?->getHappyObject() === null) {
            $happy = $this->happyObject;
            $happy->setId(1);
            $happy->setHappyMessage('We are happy');
            $extensionAttributes->setHappyObject([$happy]);
        }

        return $customer;
    }

    public function afterGetList(CustomerRepositoryInterface $subject, SearchResults $searchResults): SearchResults
    {
        foreach ($searchResults->getItems() as $customer) {
            $extensionAttributes = $customer->getExtensionAttributes();
            if ($extensionAttributes === null) {
                /** @var CustomerExtensionInterface $extensionAttributes */
                $extensionAttributes = $this->extensionFactory->create(CustomerInterface::class);
                $customer->setExtensionAttributes($extensionAttributes);
            }

            $extensionAttributes->setIsHappyCustomer(true);
            $extensionAttributes->setHappyMessage('I am so happy');
            $extensionAttributes->setHappyNumber(1);
            $extensionAttributes->setHappyList([
                "I",
                "Am"
                "Happy"
            ]);

            $happy = $this->happyObject;
            $happy->setId(1);
            $happy->setHappyMessage('We are happy');
            $extensionAttributes->setHappyObject([$happy]);

        }

        return $searchResults;
    }
}


Above code in line $happy = $this->happyObject;this is sample object. Instead of that we need to create repository with getList method which is return $items object of MageDad\Module\Api\Data\HappyObjectInterface[] And set this response to
$extensionAttributes->setHappyObject($item); This is standard way of implementation.

We can see extension attribute data like below in repository getById method
We can test using api /rest/V1/customers/:customerId

JSON
{
    .
    .
    .
    "extension_attributes": {
        "is_happy_customer": true,
        "happy_message": "I am so happy",
        "happy_number": 1,
        "happy_list": [
            "I",
            "Am",
            "Happy"
        ],
        "happy_object": [
            {
                "id": 1,
                "happy_message": "We are happy"
            }
        ]
    }
    . 
    .
    .
}
Magento2 create extension attribute for customer
Customer get API response in customer extension attribute


That’s all 😍

I hope this blog is useful to create customer extension attribute in magento2. I missed anything or need to add some more information, Don’t heisted to leave a comment in this blog, I’ll get back with some positive approach.

Keep loving ❤️ Keep inspiring 🤩 Keep liking 👍 No sharing 😂

1 Comment

  1. IWIN68 – Home page to download IWIN68 club for APK/IOS, official online reward game portal giving away code 99K at iwin68-club.net. IWIN68 is the leading online prize exchange card game portal in Asia, with many attractive games including crabs, coin toss, Sic Bo, casino, sports,… https://iwin68-club.net/

Write A Comment