Ссылка на панель управления клиентами Magento 2 отображается для конкретного пользователя?
Я хотел бы показать панель управления клиентами "Ссылка для оплаты торговых клиентов" конкретному пользователю (Например: [email protected] ) я перешел по этой ссылке Добавить новую вкладку "Входящие" в панель управления клиентами в magento 2 для добавления пользовательской ссылки в панель управления клиентами. поэтому я создал новый пользовательский модуль и внес соответствующие изменения.
Пожалуйста, найдите скриншот:
Пожалуйста, подскажите мне, как я могу это сделать.
2 answers
Пожалуйста, проверьте приведенный ниже код.
Путь шага 1 - app/code/Training/Msg/registration.php
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE,'Training_Msg',__DIR__);
Путь шага 2 - app/code/Training/Msg/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Training_Msg" setup_version="1.0.0">
<sequence>
<module name="Magento_Customer"/>
</sequence>
</module>
</config>
Путь шага 3 - app/code/Training/Customerlink/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Framework\View\Element\Html\Link\Current" type="Training\Msg\Block\Current"/>
</config>
Путь шага 4 - app/code/Training/Msg/etc/frontend/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="msg" frontName="msg">
<module name="Training_Msg"/>
</route>
</router>
</config>
Путь шага 5 - app/code/Training/Msg/Controller/Index/Msg.php
<?php
namespace Training\Msg\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\PageFactory;
class Msg extends Action
{
private $jsonFactory;
private $pageFactory;
public function __construct(
Context $context,
JsonFactory $jsonFactory,
PageFactory $pageFactory
){
$this->jsonFactory = $jsonFactory;
$this->pageFactory = $pageFactory;
parent::__construct($context);
}
public function execute()
{
//$result = $this->jsonFactory->create();
$result = $this->pageFactory->create();
$result->getConfig()->getTitle()->set("Welcome Msg");
//$data = ['msg' => 'tets'];
//return $result->setData($data);
return $result;
}
}
Путь шага 6 - app/code/Training/Msg/Block/Current.php
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Training\Msg\Block;
/**
* Block representing link with two possible states.
* "Current" state means link leads to URL equivalent to URL of currently displayed page.
*
* @method string getLabel()
* @method string getPath()
* @method string getTitle()
* @method null|array getAttributes()
* @method null|bool getCurrent()
* @method \Magento\Framework\View\Element\Html\Link\Current setCurrent(bool $value)
*/
class Current extends \Magento\Framework\View\Element\Template
{
/**
* Default path
*
* @var \Magento\Framework\App\DefaultPathInterface
*/
protected $_defaultPath;
protected $customerSession;
/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\App\DefaultPathInterface $defaultPath
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\App\DefaultPathInterface $defaultPath,
\Magento\Customer\Model\Session $customerSession,
array $data = []
) {
parent::__construct($context, $data);
$this->_defaultPath = $defaultPath;
$this->customerSession = $customerSession;
}
/**
* Get href URL
*
* @return string
*/
public function getHref()
{
return $this->getUrl($this->getPath());
}
/**
* Get current mca
*
* @return string
*/
private function getMca()
{
$routeParts = [
'module' => $this->_request->getModuleName(),
'controller' => $this->_request->getControllerName(),
'action' => $this->_request->getActionName(),
];
$parts = [];
foreach ($routeParts as $key => $value) {
if (!empty($value) && $value != $this->_defaultPath->getPart($key)) {
$parts[] = $value;
}
}
return implode('/', $parts);
}
/**
* Check if link leads to URL equivalent to URL of currently displayed page
*
* @return bool
*/
public function isCurrent()
{
return $this->getCurrent() || $this->getUrl($this->getPath()) == $this->getUrl($this->getMca());
}
/**
* Render block HTML
*
* @return string
*/
protected function _toHtml()
{
if (false != $this->getTemplate()) {
return parent::_toHtml();
}
$highlight = '';
if ($this->getIsHighlighted()) {
$highlight = ' current';
}
if ($this->isCurrent()) {
$html = '<li class="nav item current">';
$html .= '<strong>'
. $this->escapeHtml((string)new \Magento\Framework\Phrase($this->getLabel()))
. '</strong>';
$html .= '</li>';
} else {
if( $this->customerSession->getCustomerGroupId() == 1 ){
if ( strpos($this->getHref(),'msg') == false ) {
$html = '<li class="nav item' . $highlight . '"><a href="' . $this->escapeHtml($this->getHref()) . '"';
$html .= $this->getTitle()
? ' title="' . $this->escapeHtml((string)new \Magento\Framework\Phrase($this->getTitle())) . '"'
: '';
$html .= $this->getAttributesHtml() . '>';
if ($this->getIsHighlighted()) {
$html .= '<strong>';
}
$html .= $this->escapeHtml((string)new \Magento\Framework\Phrase($this->getLabel()));
if ($this->getIsHighlighted()) {
$html .= '</strong>';
}
$html .= '</a></li>';
}
}else
{
$html = '<li class="nav item' . $highlight . '"><a href="' . $this->escapeHtml($this->getHref()) . '"';
$html .= $this->getTitle()
? ' title="' . $this->escapeHtml((string)new \Magento\Framework\Phrase($this->getTitle())) . '"'
: '';
$html .= $this->getAttributesHtml() . '>';
if ($this->getIsHighlighted()) {
$html .= '<strong>';
}
$html .= $this->escapeHtml((string)new \Magento\Framework\Phrase($this->getLabel()));
if ($this->getIsHighlighted()) {
$html .= '</strong>';
}
$html .= '</a></li>';
}
}
return $html;
}
/**
* Generate attributes' HTML code
*
* @return string
*/
private function getAttributesHtml()
{
$attributesHtml = '';
$attributes = $this->getAttributes();
if ($attributes) {
foreach ($attributes as $attribute => $value) {
$attributesHtml .= ' ' . $attribute . '="' . $this->escapeHtml($value) . '"';
}
}
return $attributesHtml;
}
}
Здесь пользовательская ссылка, отображаемая в сообщении клиента только для идентификатора группы пользователей, не равна 1.
Путь шага 7 - app/code/Training/Msg/Block/Msg.php
<?php
namespace Training\Msg\Block;
use Magento\Framework\View\Element\Template;
class Msg extends Template
{
public function __construct(Template\Context $context, array $data = [])
{
parent::__construct($context, $data);
}
public function getTitle()
{
return "Test Message";
}
}
Путь шага 8 - app/code/Training/Msg/view/frontend/layout/customer_account.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="customer_account_navigation">
<block class="Magento\Framework\View\Element\Html\Link\Current" name="customer-account-navigation-myemail">
<arguments>
<argument name="path" xsi:type="string">msg/index/msg</argument>
<argument name="label" xsi:type="string">Customer Message</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
Путь шага 9 - app/code/Training/Msg/view/frontend/layout/msg_index_msg.xml
<?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="customer_account"/>
<body>
<referenceBlock name="content">
<block name="msg" class="Training\Msg\Block\Msg" template="Training_Msg::msg.phtml" />
</referenceBlock>
</body>
</page>
Путь шага 10 - приложение/код/Обучение/Msg/просмотр/интерфейс/шаблоны/msg.phtml
<?php echo $block->getTitle(); ?>
ИЛИ
Вы можете скачать модуль по ссылке github https://github.com/jothibasuj/customer-dashboard-link-based-on-condition
- Запустите обновление программы установки.
- Очистить кэш.
- установите разрешение для папки var.
Сначала Вам нужно создать класс экстентов блоков Magento\Framework\View\Элемент\Html\Ссылка\Текущий
Ваш код блока, например
namespace Namespace\Module\Block\View\Element\Html\Link;
use Magento\Customer\Model\Session as CustomerSession;
class Current extends \Magento\Framework\View\Element\Html\Link\Current{
protected $_customerSession;
/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\App\DefaultPathInterface $defaultPath
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\App\DefaultPathInterface $defaultPath,
CustomerSession $CustomerSession,
array $data = []
) {
parent::__construct($context, $data);
$this->_defaultPath = $defaultPath;
$this->_customerSession = $CustomerSession;
}
public function _toHtml(){
// Here you can check the conditions.
if($this->_customerSession->getCustomer()->getCustomAttribute()){
return parent::_toHtml();
}
return '';
}
}