Skip to main content

How to add Extension Attributes for customers in Magento 2?

Magento provides two types of attributes for entities. And here we going to learn how to add a new extension attribute in Magento. Please follow the below steps to add the extension attribute:

Step 1: Add extension attribute

Here we will add an extension attribute in extension_attributes.xml which resides under the etc folder of your custom module.

For scalar attributes:

<?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="stripe_id" type="boolean" />
    </extension_attributes>
</config>

Here, the scalar attributes indicate the simple form of attribute representation, such as an integer, a string, or a boolean. Specify the class or interface of the extension attributes inside the “for” attribute of the <extension_attributes> tag. In this case, it is the CustomerInterface. The attribute is specified with a unique code and its type.

For non-scalar attributes:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Api\CustomerRepositoryInterface">
        <plugin name="add_stripe_id" type="Magento\SomeModule\Api\Data\CustomInterface"/>
    </type>
</config>
Here, the non-scalar attributes indicate data objects such as the instance of a class. In the above example, the CustomDataInterface object is added as an extension attribute.

Step 2: Add/Update extension attribute values using Plugin

To add an extension attribute with customer data we need to add a plugin for Customer Repository. A plugin should be created for individual methods which are used like: get, save, and getById. Here we will see how to pass additional data in customer sessions. For this follow below:

Add plugin in di.xml file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Api\CustomerRepositoryInterface">
        <plugin name="add_stripe_id" type="Magento\SomeModule\Plugin\CustomerPlugin"/>
    </type>
</config>
Here I have mentioned the plugin file name as CustomerPlugin so create a file inside the Plugin folder with CustomerPlugin.php

<?php

namespace Magento\SomeModule\Plugin;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Api\ExtensionAttributesFactory;
use Magento\Customer\Api\Data\CustomerExtensionInterface;
use Magento\Framework\App\ResourceConnection;

class CustomerPlugin
{

    /**
     * @var ExtensionAttributesFactory
     */
    private $extensionFactory;

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @param ExtensionAttributesFactory $extensionFactory
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        ExtensionAttributesFactory $extensionFactory,
        ResourceConnection $resourceConnection
    ) {
        $this->extensionFactory = $extensionFactory;
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * Plugin after getById customer that adds customer's stripeId.
     *
     * @param CustomerRepositoryInterface $subject
     * @param CustomerInterface $customer
     * @return CustomerInterface
     */
    public function afterGetById(CustomerRepositoryInterface $subject, CustomerInterface $customer)

    {
        $extensionAttributes = $customer->getExtensionAttributes();
        
        if ($extensionAttributes === null || $extensionAttributes->getStripeId() === null) {
            $connection = $this->resourceConnection->getConnection();
            $select = $connection->select()->from(
                ['stripe_customers'], ['stripe_id'] 
            )->where("customer_id = ?", $customer->getId());
            $stripeId = $connection->fetchOne($select);
            $this->addStripeIdExtensionAttribute($customer, $stripeId);
        }
        return $customer;
    }

    /**
     * Set Stripe Id extension attribute
     *
     * @param CustomerInterface $customer
     * @param string $stripeId
     */
    private function addStripeIdExtensionAttribute(CustomerInterface $customer, string $stripeId): void
    {
        $extensionAttributes = $customer->getExtensionAttributes();
        if ($extensionAttributes === null) {
            /** @var CustomerExtensionInterface $extensionAttributes */
            $extensionAttributes = $this->extensionFactory->create(CustomerInterface::class);
            $customer->setExtensionAttributes($extensionAttributes);
        }
        $extensionAttributes->setStripeId($stripeId);
    }
}

Here we have added plugin for getById method only. Similiarly we can add plugin for other methods as well according to the need.

Comments

Popular posts from this blog

Unlocking Success: The Vital Role of the Contact Us Page in E-commerce

In the dynamic realm of e-commerce, where digital transactions reign supreme, the significance of customer communication cannot be overstated. Amidst the plethora of factors influencing the success of an online store, one often overlooked yet fundamentally important element is the Contact Us page. This seemingly humble corner of a website holds immense power, serving as a linchpin in fostering trust, resolving issues, and nurturing customer relationships. Let's delve deeper into why the Contact Us page is not just an afterthought but a strategic asset for e-commerce businesses, backed by proven data. Building Trust and Credibility Trust is the cornerstone of any successful e-commerce venture. According to a survey conducted by Edelman, 81% of consumers say that trusting a brand to do what is right is a deciding factor in their purchasing decisions. A prominently displayed Contact Us page with clear contact information, including a physical address, phone number, and email address, ...

Magento - LogRocket Integration

In today’s competitive eCommerce landscape, understanding user behavior is crucial for optimizing customer experiences and improving conversion rates. Magento 2, a powerful and flexible eCommerce platform, allows merchants to customize their online stores extensively. However, monitoring how users interact with these customizations is often challenging. This is where LogRocket, a modern session replay tool, comes into play. Integrating LogRocket with Magento 2 can provide invaluable insights into user behavior, performance bottlenecks, and UX issues. In this blog post, we’ll walk you through the steps to integrate LogRocket with Magento 2, and how this integration can help you improve your store’s performance and user experience. What is LogRocket? LogRocket is a session replay tool that enables you to record and playback user activity on your website. It tracks interactions such as clicks, scrolls, and form inputs, giving you a clear view of how users navigate your store. In addition,...

Using Composer Update is a Crime: Why Magento Developers Should Avoid It

As a Magento developer, managing third-party modules via Composer is essential for keeping your project organized and up to date. However, when installing a new module, there’s one command that might seem tempting, yet can lead to chaos if not used carefully: composer update Yes, you read that right—using composer update can be a crime (against your project, that is). In this blog, we’ll explore why running composer update without caution can be risky, and why you should think twice before pulling the trigger. Let’s break it down. What Does composer update Do? At first glance, composer update seems harmless. When you run it, Composer checks for newer versions of every package listed in your composer.json file and updates them to the latest compatible versions based on your version constraints. That sounds good, right? Why wouldn't you want the latest updates? Well, here's where things get tricky. The Hidden Risk of composer update Running composer update doesn't just u...