How can I get customer group name by using group id in a template (phtml
file) ?
3 Answers
If you have group id then add below code at your block class
protected $groupRepository;
public function __construct(
...
\Magento\Customer\Api\GroupRepositoryInterface $groupRepository,
...
) {
$this->groupRepository = $groupRepository;
}
public function getGroupName($groupId){
$group = $this->groupRepository->getById($groupId);
echo $group->getCode();
}
At last in phtml file you will get group name by:
$block->getGroupName($groupId)
If you want to get group name by group id at phtml using Object manager and donot want edit block class then you can use below code at phtml
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$groupRepository = $objectManager->create('\Magento\Customer\Api\GroupRepositoryInterface');
$group = $groupRepository->getById([GroupId]);
var_dump($group->getData());
echo $group->getCode();
But direct use of Object manager is not good idea,So best idea to add code at block class.
-
-
-
-
1First you should get customer load by` \Magento\Customer\Api\CustomerRepositoryInterface` for getting customer group.You will get Customer group from there.– Amit Bera ♦Apr 10, 2018 at 9:39
-
@AmitBera I loaded customer groups as your answer above, now I need to write a loop to get each customer's customer group. Can I edit above code to filter to load by customer Id or something?– JoeyApr 10, 2018 at 9:44
Update your block:
/**
* @var \Magento\Customer\Api\GroupRepositoryInterface
*/
protected $groupRepository;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Customer\Api\GroupRepositoryInterface $groupRepository
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Api\GroupRepositoryInterface $groupRepository,
array $data = []
) {
parent::__construct($context, $data);
$this->groupRepository = $groupRepository;
}
/**
* @param $id
* @return string
*/
public function getGroupNameById($id)
{
$groupEntity = $this->groupRepository->getById($id);
return $groupEntity->getCode();
}
use next code in the template:
<?php echo $block->getGroupNameById(1)?>
where the 1 is desired group id.
You should not make such requests in template files. Use blocks for it.
Add \Magento\Customer\Api\GroupRepositoryInterface $groupRepository
to the block.
And get group object like
/**
* Customer group repository
*
* @var \Magento\Customer\Api\GroupRepositoryInterface
*/
protected $groupRepository;
public function __construct(
// …
\Magento\Customer\Api\GroupRepositoryInterface $groupRepository,
// …
) {
// …
$this->groupRepository = $groupRepository;
// …
}
public function getGroupCode($groupId)
{
$group = $this->groupRepository->getById($groupId);
return $group->getCode();
}