Magento – load magento controller method from Template

template

I have two simple method inside controller

<?php   
public indexAction 
{}
public TestAction{

echo "Kkkdfd"
}

I have a template named something.phtml
How do i call testaction from my template to display php echo?

Best Answer

You don't, controllers aren't meant for that. You can call module/controller/action as url to display the echo. If you want to use a custom method to handle some logic in your template use blocks instead.

Edit: I can't help you with the library, but to finish up this answer I give you an example to create a custom block.

Create a new module in `app/etc/modules/Your_Module.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Your_Module>
            <active>true</active>
            <codePool>local</codePool>
        </Your_Module>
    </modules>
</config>

Create a module config app/code/local/Your/Module/etc/config.xml

<?xml version="1.0"?>
<config>
    <global>
        <blocks>
            <your_module>
                <class>Your_Module_Block</class>
            </your_module>
        </blocks>
    </global>
</config>

The global/blocks part defines your Block Prefix, which you can use to call it in your layout.

Create the block now in app/code/local/Your/Module/Block/Block.php

class Your_Module_Block_Block extends Mage_Core_Block_Template
{
    public function yourLogic() 
    {
        //your code here
    }
}

Now all you have to do is change your layout block to use the new custom block. Do it like this:

<block type="your_module/block" name="yourblock" template="your/template.phtml" />

The type refers to your config.xml and block file. The your_module part is the block prefix, so Your_Module_Block, and the second block part refers to the Block.php file.

In your template you can make a direct call to $this->yourLogic() now.

Hope this helps your sort things out.

Related Topic