Magento 2 : Adding custom header label and link
-
19-03-2021 - |
Question
I want to know how to add custom link to the header panel that should be manageable from back-end. so that the person trying to change the value can easily change it without any coding knowledge
I have tried it with module and it successfully worked using following code:-
<referenceBlock name="header.links">
<block class="Learning\Module\Block\Link" name="custom-header-link">
<arguments>
<argument name="label" xsi:type="string" translate="true">Customer Service: 888-371-4942</argument>
<argument name="path" xsi:type="string" translate="true">support</argument>
</arguments>
</block>
</referenceBlock>
but i dont know how to manage it from backend. thank you
La solution
You can set xsi:type="helper"
and get dynamic value from admin.For that, Follow this below steps for that :
Replace this code in your xml 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="header.links">
<block class="Learning\Module\Block\Link" name="custom-header-link">
<arguments>
<argument name="label" xsi:type="helper" helper="Learning\Module\Helper\Data::yourFunctionLabel" translate="true"/>
<argument name="path" xsi:type="helper" helper="Learning\Module\Helper\Data::yourFunctionPath" translate="true"/>
</arguments>
</block>
</referenceBlock>
</body>
</page>
Now, create yourFunctionLabel() and yourFunctionPath() in helper file for set dynamic label and path value.
Autres conseils
You just need to add 2 methods in Link.php
file
Learning\Module\Block\Link.php
and add the method below:
public function getLabel()
{
return "Customer Service: 888-371-4942"; // You can set configuration field data dynamically here
}
public function getPath()
{
return "Support"; // You can set configuration field data dynamically here
}
your layout file code should be
<referenceBlock name="header.links">
<block class="Learning\Module\Block\Link" name="custom-header-link" />
</referenceBlock>
Hope this will help you!