我想在phtml文件中获取当前的客户组ID。当我仍未登录时,将返回一般类型的客户组。如何获得适当的输出?
我想在phtml文件中获取当前的客户组ID。当我仍未登录时,将返回一般类型的客户组。如何获得适当的输出?
Answers:
Magento\Customer\Model\Session $customerSession
使用此类,您将获得当前的客户组ID
protected $_customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
echo $customerGroup=$this->_customerSession->getCustomer()->getGroupId();
endif;
}
注意:只有在客户登录后,您才能获得客户ID
您可以通过以下代码获取组ID
protected $_customerSession;
public function __construct(
....
\Magento\Customer\Model\Session $customerSession,
....
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
echo $customerGroup=$this->_customerSession->getCustomer()->getGroupId();
endif;
}
if($this->_customerSession->isLoggedIn()):
是否已登录 isLoggedIn检查?
默认情况下,Magento将清除客户会话:\Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml
。
看一看:
供应商/ magento /模块客户/模型/Context.php
/**
* Customer group cache context
*/
const CONTEXT_GROUP = 'customer_group';
/**
* Customer authorization cache context
*/
const CONTEXT_AUTH = 'customer_logged_in';
我们可以检查已登录的客户和客户组:
/**
* @var \Magento\Framework\App\Http\Context $httpContext
*/
$isLogged = $this->httpContext->getValue(Context::CONTEXT_AUTH);
$customerGroupId = $this->httpContext->getValue(Context::CONTEXT_GROUP);
将这些代码行放在您的块中。
这里还有另一个很好的解释:
尝试此操作以获取已登录和未登录客户的当前客户组ID和名称
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 current customer group ID
$collection = $this->_customerGroupCollection->load($currentGroupId);
echo $collection->getCustomerGroupCode();//Get current customer group name
}
protected $_customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
) {
$this->_customerSession = $customerSession;
}
public function getGroupId(){
if($this->_customerSession->isLoggedIn()):
echo $customerGroup=$this->_customerSession->getCustomer()->getGroupId();
endif;
}
这可能对您有用。
如果使用缓存,则使用\ Magento \ Customer \ Model \ Session可能会失败。
您最好使用:
private $sessionProxy;
public function __construct(
use Magento\Customer\Model\Session\Proxy $sessionProxy,
) {
$this->sessionProxy= $sessionProxy;
}
// may return groupId or \Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID
public function getGroupId(){
$this->sessionProxy->getCustomer()->getGroupId();
}