Magento2 – Set Customer Group from Registration Form

magento-2.1magento2

I was trying to let the customer choose the customer group while the customer registration in magento 2.

What i did was, i passed the group id on hidden field like:

<input type="hidden" name="group_id" id="group_id" value="2" />

But it is not working. When i check the customer from admin panel, the default group was chosen.

My question is:

  1. Can I change the customer group this way?
  2. I can see another method of using event observer method on customer register success but I would prefer this method if it works?

Can anyone help on this?

Thanks

Best Answer

I get to solve it so i thought answering here so that it would help others too.

What I did?

I choose event-observer approach to get this done. I created a module which track the customer register success event.You can create the module on the fly from https://mage2gen.com/ . This is very cool and it let's to create a module easily. I just created an observer with the event customer_register_success and it gives me the whole module.

It provide with the observer, with just class and few things defined.

Below is the code added by me:

<?php 


namespace Custom\Customergroup\Observer\Customer;
// added by me
use Magento\Customer\Api\CustomerRepositoryInterface;




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

/**
     * @var CustomerRepositoryInterface
     */
//added by me
    private $customerRepository;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
         CustomerRepositoryInterface $customerRepository
        )
    {
        $this->_request = $request;
        $this->customerRepository = $customerRepository;
    }
    //ends here
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ){      

        $id = $observer->getEvent()->getCustomer()->getId();
        $customer = $this->customerRepository->getById($id);

         $group_id = $this->_request->getParam('group_id');

        $customer->setGroupId($group_id);

        $this->customerRepository->save($customer);

    }
}

I have added the comment which shows my modification.

If anyone has better solution please feel free to add.

Regards

Related Topic