Magento 2:获取客户群

本文介绍了如何在Magento 2中获取所有客户组的名称和ID 。

我将在Block类中显示一个示例。您也可以在其他类(Helper / Model)中编写代码。

两种方式(依赖注入和对象管理器方式)如下所示。

使用依赖注入(DI)

这是您需要在Block类中编写的代码。

/**
 * Customer Group
 *
 * @var \Magento\Customer\Model\ResourceModel\Group\Collection
 */
protected $_customerGroup;
    
/**
 * @param \Magento\Backend\Block\Template\Context $context
 * @param \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroup
 * @param array $data
 */
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroup,        
    array $data = []
) {
    $this->_customerGroup = $customerGroup;        
    parent::__construct($context, $data);
}
/**
 * Get customer groups
 * 
 * @return array
 */ 
public function getCustomerGroups() {
    $customerGroups = $this->_customerGroup->toOptionArray();
    array_unshift($customerGroups, array('value'=>'', 'label'=>'Any'));
    return $customerGroups;
}

使用对象管理器

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$customerGroupsCollection = $objectManager->get('\Magento\Customer\Model\ResourceModel\Group\Collection');
$customerGroups = $customerGroupsCollection->toOptionArray();
//array_unshift($customerGroups, array('value'=>'', 'label'=>'Any'));
var_dump($customerGroups);

调用getCustomerGroups()方法时的输出数组将如下所示:

Array
(
    [0] => Array
        (
            [value] => 
            [label] => Any
        )
 
    [1] => Array
        (
            [value] => 0
            [label] => NOT LOGGED IN
        )
 
    [2] => Array
        (
            [value] => 1
            [label] => General
        )
 
    [3] => Array
        (
            [value] => 2
            [label] => Wholesale
        )
 
    [4] => Array
        (
            [value] => 3
            [label] => Retailer
        )
 
)

希望这可以帮助。谢谢。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论