6

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.

1 Answer 1

15

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.

17
  • hey thanks a tonn can u tell me how to update with general group to this custom customer group.? Nov 3, 2016 at 10:59
  • @supriyamishra what is your general group id ? Nov 3, 2016 at 11:00
  • for general it is 1, which is by default , i want it to get updated just after registration by 7. Nov 3, 2016 at 11:03
  • I replaced 2 by 7 in your code too Nov 3, 2016 at 11:05
  • 1
    Yeah Got it file name was misstyped Nov 3, 2016 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.