Create my account link dynamically

Here we will learn how to create an account link on my account menu section with a condition.

For that, we have to assign the custom block for the navigation

code for customer_account.xml

        <referenceBlock name="customer_account_navigation">
            <block class="JJ\Account\Block\Customer\Link" name="Account_content">
                <arguments>
                    <argument name="path" xsi:type="string">Account/index/index</argument>
                    <argument name="label" xsi:type="string">Account Management</argument>
                    <argument name="sortOrder" xsi:type="number">189</argument>
                    <argument name="navigation" xsi:type="boolean">true</argument>
                </arguments>
            </block>
        </referenceBlock>

code for the custom block –> Vendor/module/Block/Customer/link.php

<?php

namespace JJ\Account\Block\Customer;

use Magento\Customer\Block\Account\SortLinkInterface;
use Magento\Framework\View\Element\Html\Link\Current;

class Link extends Current implements SortLinkInterface
{
    protected $_customerSession;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\DefaultPathInterface $defaultPath,
        \Magento\Customer\Model\Session $customerSession,
        array $data = []
    ) {
        $this->_customerSession = $customerSession;
        parent::__construct($context, $defaultPath, $data);
    }

    protected function _toHtml()
    {
        $responseHtml = null; //  need to return at-least null
        if($this->_customerSession->isLoggedIn()) {

            $customerType = $this->_customerSession->getCustomer()->getCustomerType(); //Get the Customer Type (
            if($customerType == '1') {
                $responseHtml = parent::_toHtml(); //Return link html
            }  //Custom Condition to be checked
        }
        return $responseHtml;
    }
}

We check a custom condition and print the resultant.

Leave a comment

Your email address will not be published. Required fields are marked *