Magento 2 Customer Registration with Customer Group

customercustomer-groupmagento2

In Magento 2 , defaultly admin has to assign customer groups for all the user but I need to develop, user will select their role while register his/her account.

Best Answer

1. Add your phtml to additional info block, by creating following file: /Nano/CommissionAgents/view/frontend/layout/customer_account_create.xml.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="form.additional.info">
            <block class="Magento\Framework\View\Element\Template" name="customer_groups_additional_info_customer" template="Nano_CommissionAgents::addcustomergroup.phtml"/>
        </referenceContainer>
    </body>
</page>

2. Now create phtml file : /Nano/CommissionAgents/view/frontend/templates/addcustomergroup.phtml

<?php
$blockObj= $block->getLayout()->createBlock('Nano\CommissionAgents\Block\CustomerGroups');
$groups = $blockObj->getCustomerGroup();
?>
<div class="field group_id required">
    <label for="group_id" class="label"><span><?php /* @escapeNotVerified */ echo __('I want to register as') ?></span></label>
    <div class="control">
        <select name="group_id">
            <?php foreach ($groups as $key => $data) { ?>
            <option value="<?php echo $data['value'] ?>"><?php echo $data['label'] ?>"</option>
            <?php } ?>
        </select>
    </div>
</div>

3. Create a Block to fetch all customer groups that we have to use in phtml. Create block file at (/Nano/CommissionAgents/Block/CustomerGroups.php)

<?php

namespace Nano\CommissionAgents\Block;

use Magento\Framework\View\Element\Template;
use Magento\Customer\Model\ResourceModel\Group\Collection as CustomerGroup;

Class CustomerGroups extends Template {
    public $_customerGroup;
    public function __construct(
            CustomerGroup $customerGroup
    ) {
        $this->_customerGroup = $customerGroup;
    }

    public function getCustomerGroup() {
        $groups = $this->_customerGroup->toOptionArray();
        return $groups;
    }    
}

4. Create an Observer for event "customer_register_success". For this create an events.xml in (/Nano/CommissionAgents/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="save_customer_group" instance="Nano\CommissionAgents\Observer\SaveCustomerGroupId" />
    </event>
</config>

5. Create observer class to save customer group after registration in file (/Nano/CommissionAgents/Observer/SaveCustomerGroupId.php)

<?php

namespace Nano\CommissionAgents\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Message\ManagerInterface;

Class SaveCustomerGroupId implements ObserverInterface {
    public $_customerRepositoryInterface;
    public $_messageManager;
    public function __construct(
            CustomerRepositoryInterface $customerRepositoryInterface,
            ManagerInterface $messageManager
    ) {
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
        $this->_messageManager = $messageManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer) {
       $accountController = $observer->getAccountController();
       $request = $accountController->getRequest();
       $group_id = $request->getParam('group_id');

       try {
           $customerId = $observer->getCustomer()->getId();
           $customer = $this->_customerRepositoryInterface->getById($customerId);
           $customer->setGroupId($group_id);
           $this->_customerRepositoryInterface->save($customer);

       } catch (Exception $e){
           $this->_messageManager->addErrorMessage(__('Something went wrong! Please try again.'));
       }
    }
}

6. Now try registering after: setup-upgrade, cache flush, static-content-deply and check. Hope you will find customer group in frontend and also be able to save that group (can be verified in backend).

Related Topic