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 😂

11 Comments

  1. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  2. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  3. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  4. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  5. Reputable manufacturers adjust to GMP (Good Manufacturing Practice) requirements and use clinically tested
    components. While you need to always verify for third-party testing and transparent
    labeling, authorized steroids from trusted brands are typically thought-about secure for wholesome adults.
    Though steroids are probably dangerous and there may be proof for
    a shorter life expectancy, some do take anabolic steroids and live lengthy lives.
    We have discovered Deca Durabolin to be one of the most heart-friendly anabolic steroids.

    I received back stateside after the season was over, it was in my off-season, and I realized I was having a
    hard time simply getting away from bed, no motivation. I mean, I thought about suicide, I drank to just take a look at at some points.
    Fairly a lot every night, if not every night no much less than each other night time, I’d
    get up often between two and three in the morning and
    just sit there for 45 minutes and stare at the ceiling. I called
    them committee conferences and just kind of take into consideration what I
    was up to and the implications if it all went unhealthy,
    how ugly that was going to look. FDA can pursue regulatory
    and enforcement actions in opposition to sellers of these illegal merchandise.

    Nevertheless, this might be difficult, notably when some sellers function solely online.

    Firm names or web sites usually are simply modified, or products
    could be relabeled to evade authorities and scam consumers.

    AAOS doesn’t endorse any therapies, procedures, products, or
    physicians referenced herein. This information is
    offered as an educational service and is not meant to function medical advice.
    Anyone in search of particular orthopaedic recommendation or help
    ought to seek the guidance of his or her orthopaedic surgeon, or find one in your area through the AAOS Discover
    an Orthopaedist program on this website. Nondisclosure may compromise
    studies evaluating AAS customers to non-AAS-using weightlifters, as a end result of “non-user”
    groups are sometimes contaminated with occult AAS users (Brower et al., 1991; Ferenchick,
    1996; Kanayama et al., 2003b). Although urine testing can detect recent AAS use, individuals
    who’ve used AAS months or years earlier can’t be identified and excluded – and the
    inclusion of such individuals will result in an underestimate of effect sizes.
    Tren can be nonetheless out there in pellet kind and can be
    bought from a feed provide store and converted to injectable Tren very easily
    with a easy equipment. When sold in this form it’s not a managed substance as this
    would harm the livestock market, however it is one thing many provide
    stores hold a watchful eye on.
    There is perhaps no anabolic steroid that possesses the conditioning results of Tren. Hardness, muscular definition and vascularity,
    simply a tighter, more durable and extra pleasing physique could be produced with Tren. In fact, we’ll go so far as to say that you can combine
    any two steroids on earth they usually nonetheless wouldn’t maintain the conditioning power of Tren. When the pellets hit the
    promote it wasn’t long earlier than many athletes learned the means to convert the pellets (very giant pellets) into an injectable Tren type.
    Tren-hex (Parabolan) has also remained available in underground kind however never at the price of its older cousin Tren-a.
    Then in the early 2000’s former underground
    large British Dragon would introduce Trenbolone Enanthate, a form of Tren that solely needed
    to be injected twice a week in comparison with Tren-a’s essential every other day administration.
    DHEA, an acronym for dehydroepiandrosterone, is a pure steroid prohormone produced
    by the adrenal glands. DHEA has been marketed as a nutritional supplement since 1994 after the passing of the Dietary Supplement Well Being and Schooling Act
    of 1994. Despite being out there online and in supplement stores, DHEA remains to be considered a
    banned substance by many sports organizations.
    Primobolan (methenolone) is a banned steroid
    has been linked to several main league baseball players, together with Alex Rodriguez.
    Primobolan has lengthy been in style among athletes
    because it could construct energy without muscle bulk or many
    of the adverse unwanted aspect effects of different steroids.
    Parents and coaches ought to help young athletes perceive
    that they will excel in sports without utilizing steroids.

    Abuse of AASs has surged as they become recognised as potent image
    enhancement medicine. The primary objective of most abusers is to acquire a more engaging outward
    appearance. There are an unlimited vary of AAS substances
    illegally available, the character of their true composition is troublesome to gauge.

    Anabolic-androgenic steroids can enhance a user’s
    confidence and energy. Nevertheless, this causes customers to overlook the extreme, long-lasting, and, in some circumstances, detrimental
    effects they can trigger. The long-term administration of
    performance-enhancing medication has quite a few health dangers and
    often ends in severe adverse well being results.
    People normally take anabolic steroids by both injecting
    them immediately into the muscle or taking tablets.
    They can also come in the form of lotions or gels which are utilized on to the pores and skin.For instance, an individual may take the medicine
    for a period of time and then cease for a while. Medical Doctors can prescribe anabolic
    Steroids side Effect for various medical
    causes, but the primary is low testosterone levels that
    require long-term administration of testosterone replacement remedy.
    Lastly, they’re utilized by all kinds of athletes in nearly all sports activities.

    This brand name for fluticasone was first documented in IOC/WADA contexts round 2001 as an inhaled
    corticosteroid allowed beneath medical declaration. This stimulant was listed in the IOC doping listing
    from 1984 among psychomotor stimulants. This beta-agonist was first listed in the IOC doping list in 1988
    amongst restricted stimulants. This substance (MDMA) was first listed explicitly in the 2004 WADA
    Prohibited List as a stimulant.
    The result’s a better danger of life-threatening ailments including stroke,
    heart illness, and cerebral or pulmonary embolisms.
    The abuse or misuse of EPO also can trigger severe autoimmune ailments,
    causing the body’s immune system to assault healthy cells.
    Blood doping through transfusions additionally
    will increase the danger of infectious illness, corresponding to HIV/AIDS or hepatitis, which is
    when the liver turns into dangerously infected. The major medical use of these
    compounds is to deal with delayed puberty, some
    kinds of impotence, and losing of the physique attributable to HIV an infection or other muscle-wasting
    illnesses. Some physiological and psychological unwanted effects of anabolic steroid abuse have potential to influence
    any person, while different side effects are gender particular.

Write A Comment