Back to Top

Add a custom Customer group in Magento 2

Updated 26 May 2023

In this blog, we are going to learn how we can add a custom Customer group in Magento 2 and assign existing customers to this newly created custom customer group.

Here, in the following example, We are adding a custom Customer group in Magento 2 with the name Webkul Users, and adding all general group existing customers to this newly created group.

Please follow the below steps to achieve the desired result.

Step 1: Create an Upgrade Data file with the name UpgardeData.php file inside

the app/code/Vendor/Module/Setup/ directory.

Searching for an experienced
Magento 2 Company ?
Find out More
<?php
/** Webkul Software.
 *
 * @category Webkul
 * @package Webkul_CustomerGroup
 * @author Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */

namespace Vendor\Module\Setup;

use Magento\Customer\Api\Data\GroupInterfaceFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Customer\Api\Data\GroupInterface;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Psr\Log\LoggerInterface;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
use Magento\Customer\Model\GroupFactory;

class UpgradeData implements UpgradeDataInterface
{
    const GROUP_CODE = 'General';

    const CUSTOM_GROUP_CODE = 'Webkul Users';

    /**
     * @var GroupInterfaceFactory
     */
    private $groupInterfaceFactory;

    /**
     * @var GroupRepositoryInterface
     */
    protected $groupRepository;

    /**
     * @var State;
     */
    protected $state;
    
    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * @var GroupFactory
     */
    protected $groupFactory;

    /**
     * Intialize Dependencies
     *
     * @param GroupInterfaceFactory $groupInterfaceFactory
     * @param GroupRepositoryInterface $groupRepository
     * @param State $state
     * @param LoggerInterface $logger
     * @param CollectionFactory $collectionFactory
     * @param GroupFactory $groupFactory
     * @return void
     */
    public function __construct(
        GroupInterfaceFactory $groupInterfaceFactory,
        GroupRepositoryInterface $groupRepository,
        State $state,
        LoggerInterface $logger,
        CollectionFactory $collectionFactory,
        GroupFactory $groupFactory
    ) {
        $this->groupInterfaceFactory    = $groupInterfaceFactory;
        $this->groupRepository          = $groupRepository;
        $this->state                    = $state;
        $this->logger                   = $logger;
        $this->collectionFactory        = $collectionFactory;
        $this->groupFactory             = $groupFactory;
    }
    /**
     * Function for upgrade data
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $group = $this->groupInterfaceFactory->create();
        $group
            ->setCode(self::CUSTOM_GROUP_CODE)
            ->setTaxClassId(\Magento\Customer\Model\ResourceModel\GroupRepository::DEFAULT_TAX_CLASS_ID);
        $this->groupRepository->save($group);

        /** assign group to customers */
        $this->assignGroupToCustomers();
        $installer->endSetup();
    }

    /**
     * Function for assign group to customers
     * @return void
     */
    public function assignGroupToCustomers()
    {
        try {
            // Set the current area to adminhtml to avoid security issues
            $this->state->setAreaCode(Area::AREA_ADMINHTML);
            // Get the custom group by code

            $customGroup = $this->groupFactory->create();
            $customGroupId = $customGroup->load(self::CUSTOM_GROUP_CODE, 'customer_group_code')->getId();
            $this->logger->info("Custom Group Id :: ".$customGroupId);

            // Get all general customers
            $group = $this->groupFactory->create();
            $groupId = $group->load(self::GROUP_CODE, 'customer_group_code')->getId();
            $customerCollection = $this->collectionFactory->create();
            $customerCollection->addFieldToFilter('group_id', $groupId);
            foreach ($customerCollection as $customer) {
                // Assign the custom group to the customer
                $customer->setGroupId($customGroupId);
                $customer->save();
            }
        } catch (Exception $e) {
            $this->logger->info("Error in assign group to customers:: ".$e->getMessage());
        }
    }
}

Step 2: Now, just run the below upgrade command.

php bin/magento setup:upgrade

Now, look into the first image in which Webkul Users new group is being displayed in the customer groups section.

Look into the second image, this is before the implementation of the above code. As you can see all customers are being displayed as an existing general group.

customer-with-existing-group

And in the last image in which, As you can see all customers are being displayed with the newly created Webkul Users group.

Hope this will be helpful.

Thanks 🙂

You can see other blogs as well:-

Add Custom Product Attributes

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home