list all customer groups in Magento 2

Today we will learn how to list all customer group in magento 2. Getting the complete list of customers/users means displaying a list of all the customer groups including not logged in group as well.

So,you can get the complete list of customer groups,using following code:

Factory Method:

namespace QaisarSatti\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $groupCollection;  


  public function __construct(
     
        \Magento\Customer\Model\ResourceModel\Group\CollectionFactory $groupCollection

    ) {


        $this->groupCollection = $groupCollection;
     
    }
    public function getCustomerGroup()
    {
       
        return $this->groupCollection->create()->toOptionArray();
    }

}

Object Manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$groupOptions = $objectManager->get('\Magento\Customer\Model\ResourceModel\Group\Collection')->toOptionArray();

$fieldset->addField(
    'customer_group',
    'multiselect',
    [
        'name' => 'customer_group[]',
        'label' => __('Customer Group'),
        'title' => __('Customer Group'),
        'values' => $groupOptions,
        'disabled' => $isElementDisabled
    ]
);

One can also use the following class:

Magento\Customer\Model\Customer\Source\Group

This class provides the

toOptionArray

method which can be used to get an array of customer groups.

That’s it for this tutorial. I hope it will help you in a certain and easy way.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply