1

I am not able to get Customer group name using customer id in magento2. i have customer group id but i didn't get group name.

<?php 
    $customerObj = $objectManager->create('Magento\Customer\Model\Customer')->getCollection()->addFieldToFilter('entity_id',  $group_id);

    print_r($customer_data->getCustomerData());
?>
3

Try below code :

protected $_customerSession;

protected $_customerGroupCollection;

public function __construct(
    ....    
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Customer\Model\Group $customerGroupCollection,
    ....
) {


    $this->_customerSession = $customerSession;
    $this->_customerGroupCollection = $customerGroupCollection;

}

public function getCustomerGroup()
{
        echo $currentGroupId = $this->_customerSession->getCustomer()->getGroupId(); //Get customer group Id , you have already this so directly get name
        $collection = $this->_customerGroupCollection->load($currentGroupId); 
        echo $collection->getCustomerGroupCode();//Get group name
}
  • Thanks for your reply. I have customer object and also i have customer group id and i want customer name using customer group id without session. i want any customer group name. i have my code with customer group id. $customer_data->load($customer_id); $group_id=$customer_data->getGroupId(); $collection = $this->_customerGroupCollection->load($group_id); echo $collection->getCustomerGroupCode();//Get group name but i did'nt get customer group using my above code. now how to use $group_id for get customer group name using group id. – user3811650 Jul 29 '17 at 8:24
0

If you have customer data and know the customer group id then you can use \Magento\Customer\Model\ResourceModel\GroupRepository and you won't need customer session.

public function __construct(
   ...
   \Magento\Customer\Model\ResourceModel\GroupRepository $groupRepository,
   ...
) {
   ...
   $this->_groupRepository = $groupRepository;
}

Then in your function:

$customerGroupId = $customerData->getGroupId();
$customerGroup = $this->_groupRepository->getById($customerGroupId);
echo 'customer group name '.$customerGroup->getCode();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.