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.
Be the first to comment.