Skip to main content
2 of 2
added 1203 characters in body
Shoaib Munir
  • 9.6k
  • 10
  • 53
  • 108

You need to first create event.xml file for your observer 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>

and create observer after that Vendor\Module\Observer\ChangeCustomerGroupId.php

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class ChangeCustomerGroupId implements ObserverInterface
{

    protected $_customerRepositoryInterface;
    protected $_request;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Magento\Framework\App\RequestInterface $request,
    ) {
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
        $this->_request = $request;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getEvent()->getCustomer();
        if ($customer->getGroupId() == 1) {
            $postData = $this->_request->getPost();
            $customer->setGroupId($postData["group_id"]);
            $this->_customerRepositoryInterface->save($customer);;
        }
    }
}
Shoaib Munir
  • 9.6k
  • 10
  • 53
  • 108