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();
}
}
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
]
);
$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.