Add a custom group for customers and assign existing customers to this group

Donations Make us online

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

Here, in the following example, We are adding a custom customer group 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.

<?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 VendorModuleSetup;

use MagentoCustomerApiDataGroupInterfaceFactory;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupUpgradeDataInterface;
use MagentoCustomerApiDataGroupInterface;
use MagentoCustomerApiGroupRepositoryInterface;
use MagentoFrameworkAppArea;
use MagentoFrameworkAppState;
use PsrLogLoggerInterface;
use MagentoCustomerModelResourceModelCustomerCollectionFactory;
use MagentoCustomerModelGroupFactory;

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(MagentoCustomerModelResourceModelGroupRepository::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 🙂


Source link