Dynamically Add a Link in Customer Account Navigation in Magento 2
One of the common tasks in Magento 2 development is to add a link in customer account navigation. In each and every project developers come up with a task in which they need to add an additional link to the customer account area. Therefore, today I’m going to share a code snippet to add a link in customer account navigation.
To add a static link means the link will always display when the customer logged in, is just achieve by adding below XML file. However, to add a link dynamically in customer account navigation, you need to create an additional block file.
Add Link in Customer Account Navigation
Step 1: Create customer_account.xml
file under your module app/code/Codextblog/Demo/view/frontend/layout
directory. Add below code in the file.
<?xml version="1.0"?> <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="Codextblog\Demo\Block\View\Element\Html\Link\Current" name="customer-account-navigation-my-link" cacheable="false"> <arguments> <argument name="path" xsi:type="string">demo</argument> <argument name="label" xsi:type="string">My Link</argument> <argument name="sortOrder" xsi:type="number">10</argument> </arguments> </block> </referenceBlock> </body> </page>
Step 2: Create Block file Current.php
under your module app/code/Codextblog/Demo/Block/View/Element/Html/Link
directory. Add below code in the file.
<?php namespace Codextblog\Demo\Block\View\Element\Html\Link; use Magento\Customer\Block\Account\SortLinkInterface; use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\App\DefaultPathInterface; use Magento\Framework\View\Element\Template\Context; /** * Class Current * @package Codextblog\Demo\Block\View\Element\Html\Link */ class Current extends \Magento\Framework\View\Element\Html\Link\Current implements SortLinkInterface { /** * @var CustomerSession */ protected $_customerSession; /** * Current constructor. * @param Context $context * @param DefaultPathInterface $defaultPath * @param CustomerSession $CustomerSession * @param array $data */ public function __construct( Context $context, DefaultPathInterface $defaultPath, CustomerSession $CustomerSession, array $data = [] ) { $this->_defaultPath = $defaultPath; $this->_customerSession = $CustomerSession; parent::__construct($context, $defaultPath); } protected function _toHtml() { if (conditon) { return parent::_toHtml(); } else { return null; } } public function getSortOrder() { return $this->getData(self::SORT_ORDER); } }
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me