Monday, October 19, 2009

Simple steps to create a custom module.

Creating custom modules is one of the important part of magento. Its allow you to insert functionality anywhere, whether in a “static” block fashion that’s more than static, or a shipping/payment module, or large module.

We will start with a very basic example.
Step 1.
First allow magneto to know about your new module. Create a xml file at app/etc/modules/Unique_All.xml. Notice _All, it indicates that you can declare all your modules here.

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

Step 2.
Now create a configuration file for your new module. app/code/local/Unique/Example/etc/config.xml

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

Step 3.
Create block code. It doesn't do anything but show some functionality.

<?php
class Unique_Example_Block_View extends Mage_Core_Block_Template{
private $message;
private $att;

protected function createMessage($msg) {
$this->message = $msg;
}

public function receiveMessage() {
if($this->message != '') {
return $this->message;
} else {
$this->createMessage('Hello World');
return $this->message;
}
}

protected function _toHtml() {
$html = parent::_toHtml();

if($this->att = $this->getMyCustom() && $this->getMyCustom() != '') {
$html .= '
'.$this->att;
} else {
$html .= '
No Custom Attribute Found';
}

return $html;
}
}
?>

Step 4.
Create template (phtml) file.
app\design\frontend\default\unique\template\example\view.phtml

<div>
<span><strong>This is the output of the unique example:</strong></span><br /><span style="color:#FF9933;">
<?php
echo $this->receiveMessage();
?>
</span>
</div>

Yours custom module is ready to use.
In CMS page add below code, where you want to use.

{{block type="unique_example/view" my_custom="Test" template="example/view.phtml"}}

Or something like this in the Layout Update XML area (Custom Design area in a CMS page)

<reference name="right">
<block type="unique_example/view" my_custom="Test" template="example/view.phtml" />
</reference>

No comments:

Post a Comment