Magento2 Event Observer – How to Update Customer Group on Customer Register Success

customer-groupevent-observermagento2

I want to set a customer group as first time user for that I am using an observer so that I can update the customer group just after or on the same time of registration.

Best Answer

First create your configuration file in Vendor\Module\etc\frontend\events.xml :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_register_success">
        <observer name="persistent" instance="Vendor\Module\Observer\ChangeCustomerGroupId" />
    </event>
</config>

Then create the observer Vendor\Module\Observer\ChangeCustomerGroupId.php

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class ChangeCustomerGroupId implements ObserverInterface
{
    const CUSTOMER_GROUP_ID = 2;

    protected $_customerRepositoryInterface;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    ) {
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getEvent()->getCustomer();
        if ($customer->getGroupId() == 1) {
            $customer->setGroupId(self::CUSTOMER_GROUP_ID);
            $this->_customerRepositoryInterface->save($customer);;
        }
    }
}

NB: don't forget to replace 2 with the id of the customer group you want to use.

Related Topic