0

I need to link already registered user to the customer group. I'm trying to solve it using event and observer. User will receive a link and logging in using the present link, the customer will be attached to the new customer group

<?php 


namespace Limegrow\CustomerGroupJoin\Observer;

use Magento\Customer\Api\CustomerRepositoryInterface;




class CustomerLoginSuccess implements \Magento\Framework\Event\ObserverInterface {

/**
 * @var CustomerRepositoryInterface
 */

private $customerRepository;
private $groupCollectionFactory;

public function __construct(
    \Magento\Framework\App\RequestInterface $request,
     CustomerRepositoryInterface $customerRepository,
     \Magento\Customer\Model\ResourceModel\Group\CollectionFactory $groupCollectionFactory
){
    $this->_request = $request;
    $this->customerRepository = $customerRepository;
    $this->groupCollectionFactory = $groupCollectionFactory;

}

public function execute(
    \Magento\Framework\Event\Observer $observer
){      

    $id = $observer->getEvent()->getCustomer()->getId();
    $customer = $observer->getEvent()->getCustomer();    
    $invite_code = $this->_request->getParam('invite_code');
    $groupCollection = $this->groupCollectionFactory->create();
    $groupCollection->addFieldToFilter('invite_code', $invite_code);
    foreach ($groupCollection as $group) {
        $customer->setGroupId($group->getId());
        $this->customerRepository->save($customer);
    }
}

}

Currently a customer can log in, however, the group will be unchanged.

  • What is the observer name you use to handle it? How do you declare your observer? Is your observer executed when user login? – Rendy Eko Prastiyo Aug 21 at 19:51

Your Answer

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

Browse other questions tagged or ask your own question.