Reading list Switch to dark mode

    List all customer groups in Magento 2

    Updated 22 February 2024

    Today we are discussing how to get the list of all customer groups in Magento 2.

    To show this, we have used an example of an admin block as shown below:

    <?php
    namespace Webkul\CustomModule\Block\Adminhtml;
    
    class CustomerGroups extends \Magento\Backend\Block\Template
    {
        /**
         *
         * @var \Magento\Customer\Model\ResourceModel\Group\Collection
         */
        protected $_customerGroupColl;
    
        /**
         * @param \Magento\Backend\Block\Template\Context $context
         * @param \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroupColl
         * @param array $data
         */
        public function __construct(
            \Magento\Backend\Block\Template\Context $context,
            \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroupColl,
            array $data = []
        ) {
            $this->_customerGroupColl = $customerGroupColl;
            parent::__construct($context, $data);
        }
    
        /**
         * Function to get customer groups array
         *
         * @return array
         */
        public function getCustomerGroups()
        {
            $customerGroups = $this->_customerGroupColl->toOptionArray();
            return $customerGroups;
        }
    }

    Here, $_customerGroupColl is an object of Magento\Customer\Model\ResourceModel\Group\Collection class.
    In the function getCustomerGroups we use a method: toOptionArray() which returns the array of all customer groups in Magento 2 that have their id and title.

    Hope it will help you. Thank you.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    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