How to Dynamically Add Link to Customer Account Navigation in Magento 2
Magento 2 eCommerce CMS allows customizing the default features based on the business requirements. Magento offers a rule-based condition field using which the admin can easily configure the condition-based features.
While creating a navigation link on my account dashboard, you need to create a customer file as static. But, at times, you need to change it to dynamic. This is not possible in default Magento.
For an instance, in Multi-vendor extension, there are multiple types of sellers such as retailers, wholesalers, general. So, every customer group requires different functionalities that might be unnecessary for others. Custom options are needed for the sellers to add a new product. In such a case, it displays such options to sellers only. Whereas, for the customers, such an option is not visible.
However, you can easily create a custom link dynamically using the code provided here. I have provided a complete solution to dynamically add link to customer account navigation in Magento 2 below.
Method to Dynamically Add Link to Customer Account Navigation in Magento 2:
Create customer_account.xml file under app/code/Vendor/Module/view/frontend/layout
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?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="Vendor\Module\Block\Customer\DynamicLink" name="customer-navigation-dynamic-link" after="-"> <arguments> <argument name="label" xsi:type="string">Dynamic Link</argument> <argument name="path" xsi:type="string">customer/dynamicLink/index</argument> </arguments> </block> </referenceBlock> </body> </page> |
Create DynamicLink.php file under app/code/Vendor/Module/Block/Customer/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php namespace Vendor\Module\Block\Customer; use Magento\Framework\View\Element\Html\Link\Current; use Magento\Framework\View\Element\Template\Context; use Magento\Framework\App\DefaultPathInterface; use Magento\Customer\Model\Session; class DynamicLink extends Current { protected $customerSession; public function __construct( Context $context, DefaultPathInterface $defaultPath, Session $customerSession, array $data = [] ) { $this->customerSession = $customerSession; parent::__construct($context, $defaultPath, $data); } protected function _toHtml() { $responseHtml = null; if($this->customerSession->isLoggedIn()) { // here you can put your custom conditions $responseHtml = parent::_toHtml(); } return $responseHtml; } } |
That’s it.
Please mention any doubts about the event in the Comments section below. I’d be happy to help you.
Also, I’d be grateful if you could share the solution with the Magento community via social media.
Thank you.