I am sure many of you have once faced the necessity of creating links in ‘My account’ or ‘Toplinks’ menu. It is quite simple to implement – just add the following code into xml:
1 2 3 4 5 6 7 8 9 |
<customer_account> <reference name="customer_account_navigation"> <action method="addLink" translate="label" module="mymodule"> <name>mylink</name> <path>mymodule/myblock</path> <label>My Link</label> </action> </reference> </customer_account> |
After that all you need is to create an appropriate controller (mymodule/myblock/index), a template for the content (mymodule/myblock.phtml), a block (mymodule/myblock) and to define them in the xml:
1 2 3 4 5 6 7 8 9 10 11 |
<mymodule_myblock_index> <update handle="customer_account"/> <reference name="root"> <action method="setTemplate"> <template>page/2columns-left.phtml</template> </action> </reference> <reference name="content"> <block type="mymodule/myblock" name="mymodule_myblock" template="mymodule/myblock.phtml" /> </reference> </mymodule_myblock_index> |
The only drawback is that the link is a static one, so it does not depend on any conditions or events. The easiest way to make it dynamic (dependent on events and conditions) is to use Magento events together with handles.
First off, let’s change the default handle <customer_account> to the custom handle <random_name_handle> in the aforementioned xml:
1 2 3 4 5 6 7 8 9 |
<random_name_handle> <reference name="customer_account_navigation"> <action method="addLink" translate="label" module="stores"> <name>mylink</name> <path>mymodule/myblock</path> <label>My Link</label> </action> </reference> </random_name_handle> |
Next we assign an observer to the event <controller_action_layout_load_before>:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<frontend> … <events> <controller_action_layout_load_before> <observers> <mymodule_name_controller_action_layout_load_before> <type>singleton</type> <class>mymodule/observer</class> <method>myLink</method> </mymodule_name_controller_action_layout_load_before> </observers> </controller_action_layout_load_before> </events> … </frontend> |
Creating an appropriate observer and a method for it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public function myLink(Varien_Event_Observer $observer) { if (in_array($this->getGroupId(), Mage::helper('mymodule')->getAllowedGroups())) { $observer->getEvent()->getLayout()->getUpdate()->addHandle(‘random_name_handle’); } } public function getGroupId() { $login = Mage::getSingleton( 'customer/session' )->isLoggedIn(); if($login) { return Mage::getSingleton('customer/session')->getCustomerGroupId(); } return FALSE; } |
The key point – $observer->getEvent()->getLayout()->getUpdate()->addHandle(‘random_name_handle’) – adds the handle <random_name_handle> and thereby adds the link if the condition is true.
Magento Custom Development
Take your online store to the next level with BelVG Magento Custom Development
Visit the page
Very useful, and good approach. Thank you.