General

How to Lock Customer Account if They belong to Specific Customer Group in Magento 2

Requirements differ from business to business and the one who fulfills every need can be known as ultimate. When it comes to eCommerce, Magento does provide a one-stop solution to the store owner to fulfill customer needs and serve a seamless shopping experience to their shoppers. And definitely store owner’s requirement is endless but Magento never failed.
Recently one of our customers wanted to create one customer group inside his Magento 2 store and when he adds any customer to that group, their account should be automatically get locked and it should not be accessible anymore. He got this idea to prevent spamming inside his store. To end his search he came to us and being helping hands to our customers is a core value. Maybe you have come across a situation in the past or looking for the same. So here is code that will help you to lock your customer account when it falls in a specific group of Magento 2.
For this purpose, we have to make use of the customer_login event observer to collect customer group after login and then logout.
To do the same first you need to open the “Events.xml” file located at the below path.

app\code\Vendor\Extensionetc\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_login">
        <observer name="customer_login_observer" instance="Vendor\Module\Observer\CustomerLogin" />
    </event>
</config>

Now you need to create one more file named “Customerlogin.php” file at the below path.

app\code\Vendor\Extension\Observer\CustomerLogin.php

<?php
namespace Vendor\Extension\Observer;
use Magento\Framework\Event\ObserverInterface;
class CustomerLogin implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\ResponseFactory
     */    private $responseFactory;
    /**
     * @var \Magento\Framework\UrlInterface
     */    private $url;
    private $customerSession;
    private $messageManager;

    public function __construct(
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->responseFactory = $responseFactory;
        $this->url = $url;
        $this->customerSession= $customerSession;
        $this->messageManager = $messageManager;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getEvent()->getCustomer();
        $customerGroup = $customer->getGroupId();
        if($customerGroup==22)
        {
            $this->customerSession->logout();
            $this->messageManager->addErrorMessage(__('You are Locked'));
            $redirectionUrl = $this->url->getUrl('[SET YOUR URL HERE]');
            $this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();
            return $this;
        }
    }
}

That’s it. Now extension works flawlessly to lock customer account if they fall into a specified customer group and they will get the message that “You are Locked” if they try to log in and get redirected to a specified URL.

Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issues while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 8 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago