3

I have a customer registration form, and an additional field I want to assign a customer to specific group id on if he selected the custom field in the form. please suggest any solution for how to save a customer to a specific group.

2 Answers 2

3
  1. Create app/code/companyname/modulename/etc/frontend/events.xml using customer_save_after event:

  2. Create Companyname\Modulename\Observer\SetGroup.php

    <?php
    
    namespace Companyname\Modulename\Observer;
    
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Customer\Api\CustomerRepositoryInterface;
    
    class SetGroup implements ObserverInterface
    {    
        private $customerRepository;
    
        public function __construct(
            \Magento\Framework\App\RequestInterface $request,
             CustomerRepositoryInterface $customerRepository
        )
        {
            $this->_request = $request;
            $this->customerRepository = $customerRepository;
        }
    
        public function execute(
            \Magento\Framework\Event\Observer $observer
        )
        {          
            $id = $observer->getEvent()->getCustomer()->getId();
            $customer = $this->customerRepository->getById($id);
    
            $groupId = $this->_request->getParam('groupId');    
            $customer->setGroupId($groupId);    
            $this->customerRepository->save($customer);    
        }
    }
    
0
1

The above code is going to create an infinite loop, because every time the customer is saved the event will be triggered and the observer will keep executing until it crashes.

Adding a stop condition should fix the issue:

$groupId = $this->_request->getParam('groupId');    
if ($groupId !== $customer->getGroupId()) {
    $customer->setGroupId($groupId);    
    $this->customerRepository->save($customer);    
}

Alternatively, you can also use this extension: Customer group selector [M2]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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