Search code examples
magentomodulehyperlinkblock

Magento: how to add a link via code to a block of a custom module?


I'm trying to add a link to one of my blocks to a specific action of one of my controllers. Looking through the class docs and googling didn't resolve something useful. (maybe I just used the wrong search queries).

My Controller has two actions:

indexAction() and exportAction()

Now, in one of my blocks I wand to add link to exportAction(). I've found the method addLink() but this doesn't work.

Maybe anyone knows how to do that ? Or could point me to the right resources on the net ?

Regards, Alex

Block Example:

<?php

class Polyvision_Tempest_Block_Adminhtml_View extends Mage_Adminhtml_Block_Template
{
    public function __construct()
    {
        parent::__construct();
    }

    protected function _toHtml()
    {

    $html = "whatever";

        return $html;
    }
}
?>

Solution

  • Your question isn't clear/complete.

    A block renders HTML, either through a phtml template or through PHP code. To add an HTML link, you just render a html anchor tag with an href

    //via PHP
    protected function _toHtml()
    {
        $html = '<a href="<?php echo $this->url('frontname/controllername/action/key/value/key/value');?>">My Link</a>';
        return $html;
    }     
    
    
    //via phtml template
    
    #your block
    class Polyvision_Tempest_Block_Adminhtml_View extends Mage_Adminhtml_Block_Template
    {
        protected function _construct()
        {
            $this->setTemplate('path/to/from/template/folder/as/basetemplate.phtml');
        }
    }
    
    #your template
    <a href="<?php echo $this->url('frontname/controllername/action/key/value/key/value');?>">My Link</a>';
    

    The addLink method is a special method that only applies to certain types of blocks. When you call it it add links information to the block's data properties. Then, it's _toHtml method or phtml template has been written such that it loops over the stored data to output links. It doesn't apply to general blocks, which is what makes your question confusing.

    Hope that helps!