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
Create
app/code/companyname/modulename/etc/frontend/events.xml
usingcustomer_save_after
event: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); } }
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]