Create a simple custom module

Posted on 11. Sep, 2008 by Fido in Development, Magento, Module

Part of customizing Magento is, of course, creating custom Modules. These allow you to inject functionality anywhere, whether in a “static” block fashion that’s more than static, or a shipping/payment module, or large module to do something as large as integrating a 3rd party system (or multiple systems).

There are many things custom Modules can do, from editing your Database, to handling module upgrades to overriding classes (Blocks, Controllers, Models) … and more!

This blog post is a very basic start on creating your own custom module and hooking it up to a phtml file in your own theme.

I will be creating a Fido Example module. ‘Fido’ is the namespace (vs Mage), ‘Example’ is the module (vs Catalog, Page, Core, Shipping etc).

Step One

Inform Magento that you have a custom module.
app/etc/modules/Fido_All.xml Notice the _All in the xml file name. I can declare all of my modules here. (Say I have more than Example, I can also declare my Example2 module in this file).

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

I have informed Magento that I have an active module (you can turn it off from here by setting ‘active’ to false. I have also informed Magento that it is located in the ‘local’ code pool.

Step Two

Configure your new module. Note the file locations (need to create directories as necessary).
app/code/local/Fido/Example/etc/config.xml

<?xml version="1.0"?>
<config>
<modules>
<Fido_Example>
<version>0.1.0</version>
</Fido_Example>
</modules>
<global>
<blocks>
<fido_example>
<class>Fido_Example_Block</class>
</fido_example>
</blocks>
</global>
</config>

I have informed Magento of my module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).

I have also informed Magento that my module contains  block files which are found in fido/example/block. My class name will have “Fido_Example_Block”. If you want to see the many possibilities of stuff that goes in here, check out Mage config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there. Those explanations are for another post.

Step Three

Here is my block code. It doesn’t really do anything, but shows some functionality.
app\code\local\Fido\Example\Block\View.php

<?php
/**
* Example View block
*
* @codepool   Local
* @category   Fido
* @package    Fido_Example
* @module     Example
*/
class Fido_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 .= '<br />'.$this->att;
} else {
$html .= '<br />No Custom Attribute Found';
}

return $html;
}
}

The function receiveMessage() just returns “Hello World”
The function _toHtml() is responsible for outputting the template associated with the block. Make sure you run paret::_toHtml and return it as part of any other items returned in that function!

Step Four

Here we create our template (phtml) file.
app\design\frontend\default\fido\template\example\view.phtml

<?php

/**
* Fido view template
*
* @see Fido_Example_Block_View
*
*/
?>
<div>
<span><strong>This is the output of the fido example:</strong></span><br />
<span style="color:#FF9933;">
<?php
echo $this->receiveMessage();
?>
</span>
</div>

This just outputs some HTML and also runs the receiveMessage() function from our block (view.php).

Two caveats here. By placing our view.phtml file in it’s location, we have created our own theme. You must make sure that
a) Magento knows about your theme (Admin->System->Design)
and
b) If you use the this block in a CMS page, you set the CMS page to use your theme (Admin->CMS->Manage Pages->’Your Page’->Custom Design->Custom Theme drop down)

You’re custom module is now ready for use.

In a cms page, add this to your content:

{{block type="fido_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="fido_example/view" my_custom="Test" template="example/view.phtml" />
</reference>
//this will add your block in the right column

Now you should successfully have your block and the Hello World message being displayed (on your CMS page).

Notice what doesn’t work? Your custom attribute. In 1.1.2, the custom attribute doesn’t seem to be working as it did before. I’ll be investigating what changed.

Tags: , , , , ,

53 Comments

Fido

11. Sep, 2008

Sorry for the lack of proper formatting in the XML files there. I need to find a better code plug-in.

Dinesh

13. Sep, 2008

I got this error while executing the module.

Parse error: syntax error, unexpected ‘;’ in E:\Program Files\Apache Group\Apache2\htdocs\magento\app\code\local\Fido\Example\Block\view.php on line 31

Fido

13. Sep, 2008

I updated the post so wordpress parses it correctly. It turned ‘&&’ into a garble.

Cale

23. Sep, 2008

I got the same result as Dinesh, I guess I didn’t catch the result of the solution. What do I need to change to fix the unexpected ‘;’ on line 32 in the output? Is it really something I need to change in View.php? preciate the help with this post by the way. Thanx homey :)

~cale

Fido

23. Sep, 2008

I’ve once again fixed it – Wordpress / my code plugin seems to enjoy getting confused with the symbol ‘&’ (HTML needs to see ‘&’ to output the ampersand properly).

@Cale – yes, it’s the IF statement you see in view.php

Qasim

02. Oct, 2008

I got this error:
Fatal error: Cannot redeclare class Fido_Example_Block_View in C:\xampplite\htdocs\magento-1.1.6\magento\app\code\local\Fido\Example\Block\Example.php on line 46

Wat to do to fix it?

Fido

02. Oct, 2008

My code doesn’t even have that many lines (46), so I assume you are adding or editing it – I would have to see your code to give you any fruitful answer.

Cale

08. Oct, 2008

Hey thanx for the post. so, I see where I need to fix the problem in the if statement in view.php do I change “&amp;&amp;” to something else? for instance “&&” as you referenced earlier? And leaving out the semi colons? I’m kind of a hack with scripting haha :/ Thanx again; this has been
very helpful.

Fido

08. Oct, 2008

You replace each “&” with “&”

Reason being is “&” is simply an encoded ‘&’

HTML uses the encoded version and interprets it as an ampersand.

for instance, in HTML, “My Text & Text” will display as “My Text & Text”

This is an HTML thing, not a PHP code thing.

Fido

08. Oct, 2008

See, even in my comment above, Wordpress decided to change my “& amp ;” to an ampersand :P

Cale

09. Oct, 2008

So I’ve gotten it to work with out any errors in the output. But, I also don’t see anything on my magento home page where I put the layout update. Is there another test I can try? Just to see what is coming thru. Also, in what file should I place a rotating banner ad script that I want to use as my module functionality?
The view.phtml file? If so, would I still be able to use this script below… (real basic)

from this url:

http://www.tutorialcode.com/javascript/rotating-banners/

Cale

09. Oct, 2008

Also do you know if this script and module will work in conjunction with Paper Click? (A Banner Ad service, to sell advertising on the site)

Thanx again.

Fido

09. Oct, 2008

You should put all HTML output in the view.phtml file. (including any on-page javascript). You can use your .php file to create output that is echo’ed out on the .phtml file if you wish also (this is what my simple example does with the “receiveMessage” function.

I’m not sure about your error – it could be a million different things (are you referencing the name “right” ? Are you editing a stock template? Do you have a right column? (using 3 or 2-column right layout?)

You can use a module like this to output “pay per click” ads. (Or Paper click…?). You can also use static blocks for them, as static blocks are useful for straight up HTML / javascript code (just not PHP)

Cale

10. Oct, 2008

Okay cool. Yes it is referenced to the right column. I have cross referenced other stock modules before, and they didn’t show up (like changing from “left” to right” in the xml layout files) and they just disappear. And the cache is disabled. Here is the link to the site if you are willing to check it out. The fact that I don’t have any errors in the output tells me, it’s working. Just not sure what else I could try to output.

http://www.allpromo.net

Thanx again

Cale

10. Oct, 2008

Also can you recommend any references for how to set up the rest of the banner rotator? like what pay per click service to choose for a new no-traffic site, whether or not they use flash banners/static image banners, what size to design for, what scripts I will need to embed, where I will be adding the xml, something that covers all the angles. The magento site is useless as a reference to me for this concept. If there is any information there it’s not specific enough to what I’m applying to (banner rotator modules or blocks) If it is it’s Way over my head. If not, no worries. I’ll be just as lost as before :) Thanx again for your time. I’m naked and fearless.

Sin Celery,

*cale

Fido

10. Oct, 2008

I’m not sure what to recommend other than use our contact form to inquire about some professional services. This is something we can do on an hourly or by-scope process if you are interested. Basically there is probably some small problem with what you are doing. Without getting into the back end, I’m not sure what I can do from this message board.

Good luck!

Vitor Braga

13. Oct, 2008

Works perfectly! Conglatulations for this post!

aledujke

15. Oct, 2008

Thanks! Works like a charm! btw did you tried getting your attribute with:

$this->getData(’my_custom’)

It worked for me when I call it from view.phtml it maybe works from view.php :?

Cheers!

Fido

15. Oct, 2008

Thanks – I’ll try that out!

Tobi

13. Nov, 2008

Thank you a lot for this great tutorial. All works fine!!

Cowboy

14. Nov, 2008

I got it working thanks for the tutorial.

However for some reason the custom attribute is not working. I always get “No Custom Attribute Found” back from the new component. I cannot seem to get a handle to the attribute.

I’ve tried the thing that worked for aledujke but that does not work either.

Any ideas?

Sir

18. Nov, 2008

Hi
I am trying to reproduce your module, but it does not show up in the content. I already tried many custom module tuts, but no one displayed anything in the content. Coudl you perhaps tell me what I did wrong. Did do the the following steps:
I have created 4 files in the directories you named above, I have deleted all “o”(these break things) in each file.
In the CMS page I did paste the code:
{{block type=”fido_example/view” my_custom=”Test” template=”example/view.phtml” }}
But there is nothing shown in the content. I want use it for some CMS sites where I need to put in more HTML Code than the database can save. Is there another possibility than writing a custom module?

Bill

21. Nov, 2008

Thanks for this tutorial – I just got it to work.

One question on the custom attribute. I commented out a line and added a new line in View.php:

//if($this->att = $this->getMyCustom && $this->getMyCustom != ”) {
if($this->att = $this->getData(’my_custom’) && $this->getData(’my_custom’) != ”) {

The output I expected is “Test”, but instead I’m seeing “1″. That’s weird, I think… Is it a boolean? Or something else?

Fido

21. Nov, 2008

Cowboy – Correct, that does not work, but as far as I’ve read, should. (This was noted at the end of the article)

Sir – I’m not sure I can figure that one out without seeing the files

Bill – I’m not sure why that is outputting “1″ (or where it is outputting). As was noted in the article, the custom attribute was something we could not get working (but should have been able to according to things we’ve read)

Friederike

08. Dec, 2008

Thank you very much for this nice tutorial. I had many attempts to run my own modul last week and now I’m happy with this here. For all who could not see anything on the screen, no hello world and no error, try to define the version in the config.xml of your module. See Step 2 above. Without that I had no output.

I also had trouble with the custom pamater. I also had the output “1″. I put the following in the view.phtml instead of the php file:

if($this->getData(’my_custom’) && $this->getData(’my_custom’) != “”) {
echo ”.$this->getData(’my_custom’);

} else {
echo’No Custom Attribute Found’;
}

Good Luck!

osdave

15. Dec, 2008

hey Fido, thanks a lot for this tutorial: it is really helpfull!
I’ve take it as a model for me to explain in spanish how to create a dropdown for adding to cart products, i hope you don’t mind (I’ve put a link to this tutorial, of course).
Looking forward to read more tutorials,
cheers

Fido

15. Dec, 2008

Of course we don’t mind!

We don’t require any recognition, but of course it’s always appreciated!

Use anything here as you wish :)

Gayatri

24. Dec, 2008

Hi Fido,

I tried out your tutorial and it worked for me when I changed the config.xml to this

0.1.0

Fido_Example_Block

The difference being in the tag I had to rename to just !! Hope, this note will help some one :)

Thank you very much for the tutorial! It definitely got me to a good start.

Srdjan

24. Dec, 2008

Thanks for the tutorial, it’s really straightforward. I’ve got my module to work when called from i.e. catalog.xml, but I can’t get magento to read my new layout file, called banners.xml. I thought that by specifying it in Mage_all.xml it will get red, but it doesn’t. Where do I have to inform Magento to check my banners.xml for includable blocks?

Siva

30. Dec, 2008

thanks a lot for giving hints

Siva

30. Dec, 2008

How to add custom attribute as it is showing no custom attribute found…

Subesh Pokhrel

06. Jan, 2009

Thanx that helped me a lot.. but I used Default template.. Coz yours did not workk.

David

07. Jan, 2009

Great tutorial!

I figured out why the custom attribute is returning a ‘1′ (a boolean value). Try this code:

if(($this->att = $this->getData(’my_custom’)) && $this->getData(’my_custom’) != ”) {

Notice the extra parentheses to separate the setting of the value from the second test. Hope this helps.

Mazhar

09. Jan, 2009

Hey fido. you are awesome dude. me quite jealous. :)
i am trying to have a picture voting system on my magentosite. i got how to get pic poll on the community poll but i am not able to get it to the center of the page. like in a static block. like in a admin…CMS<manage Pages<New Page

i also tried to download and get a free PHP picpoll script working but i am lost (the amazing little picpoll)…but I think your this post is the answer.

Any suggestions do PM me at meganto forum (SelfSuicide) or mail me.

Thanks and let me work my rookie mind now..

Graeme

09. Jan, 2009

Thanks for the lucid explanation.

I’ve run through this on Magento 1.1.8 and found one problem:

file app\code\local\Fido\Example\Block\View.php

has to be saved as

app\code\local\Fido\Example\Block\view.php

otherwise my installation (*nix with apache) did not ’see’ the view.phtml file

zmove

09. Jan, 2009

Hi,

I tried this tutorial on a 1.2.1. Just replaced the name of the module by mine (I took care to respect upper and lower case). I work on a custom interface (a copy of blank interface renamed).

But I can’t make this block work. I have the module activated in admin, I put the code of the block in my homepage, but my homepage is still empty. Impossible to get something. No error at all except that nothing seens to be executed.

Where could I investigate to understand the origin of the problem ?

thanks

zmove

[...] and create your own template for over-riding core modules with your custom code, creating your own custom modules and your own template files. Also get jQuery working properly if you plan on using [...]

David

19. Jan, 2009

@zmove:

Have you tried refreshing your cache?
(Admin > System > Cache Management)

indi

27. Jan, 2009

Hi friends,

If you want to make a hassel free custom module then follow this link. This may help you,

http://www.magentocommerce.com/wiki/custom_module_with_custom_database_table

Fido

27. Jan, 2009

Note: The above link to the wiki has been out there for a while and is a great learning resource – However I believe it is still slightly outdated. It looks like the last update was in August of ‘08

Still something to checkout if you have not yet.

bluesea

21. Feb, 2009

Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 64: parser error : Comment not terminated in E:\projects\magento-1.2.1\magento\app\code\core\Mage\Core\Model\Layout\Update.php on line 293
Trace:
#0 E:\projects\magento-1.2.1\magento\app\code\core\Mage\Core\Model\Layout\Update.php(293): mageCoreErrorHandler(2, ’simplexml_load_…’, ‘E:\projects\mag…’, 293, Array)
#1 E:\projects\magento-1.2.1\magento\app\code\core\Mage\Core\Model\Layout\Update.php(319): Mage_Core_Model_Layout_Update->fetchFileLayoutUpdates(’

Above is erroe report.
I cann’t find the problom.

sunil

05. Mar, 2009

hall fido i have done it with ur help but it failed.. beter luck next time but u tried well,, thanks

sunil

05. Mar, 2009

same error which is mentioned by dinesh ok plese do something for it…

Fido

05. Mar, 2009

I have tested this by creating a new module within Magento vs 1.2.1 and copying and pasting from this post exactly – I could not replicate the error.

Fanck

05. Mar, 2009

@Fido

You got it working on 1.2.1 with no change? because I have the same issue as zmove (blank)

thanks

Fido

05. Mar, 2009

Correct –
No change at all besides the obvious deleting of the line numbers when you copy and paste from above. (I did NOT use the “copy to clipboard” or the “view plane” option, which might be the difference).

Fido

05. Mar, 2009

Also be very wary of this blog entering in ampersand code, since it likes to change & to the HTML entity “& amp ;” (with no spaces).

Charles

30. Mar, 2009

Hey, guys! Hello from Brazil :)

I’m really fresh on creating Magento Modules, so the post was way useful for me. However, I had to add a few lines to my app/local/code/…/…/etc/config.xml

I’d wish to know if anybody knows, by any chance, why I needed to do such a thing.

I named my namespace as “Binworks” and my module as “Imprensa”, so with the addictional lines, my config.xml got to something like this:

[code language="xml"]

0.1.0

Binworks_Imprensa_Block

standard

Binworks_Imprensa
imprensa

[/code]

Charles

30. Mar, 2009

Ow.. we should have an “preview” function here… the code above should be like this (hope that it’s ok this time)

<?xml version=”1.0″?>
<config>
<modules>
<Binworks_Imprensa>
<version>0.1.0</version>
</Binworks_Imprensa>
</modules>
<global>
<blocks>
<Binworks_Imprensa>
<class>Binworks_Imprensa_Block</class>
</Binworks_Imprensa>
</blocks>
</global>
<frontend>
<routers>
<Imprensa>
<use>standard</use>
<args>
<module>Binworks_Imprensa</module>
<frontName>imprensa</frontName>
</args>
</Imprensa>
</routers>
</frontend>
</config>

nirmesh

03. Apr, 2009

hi fido,

i have made the custom module as per u mentioned block Fido_Example is also appearing in conguration->advance tab but nothing is displaying when i m previewing that example cms page.
is there any way i can track that my view.php and viw.phtml files are calling or not?

please reply ASAP I WOULD BE GRATEFUL TO U

Battista

20. Apr, 2009

Hello!

I’m trying to create a custom module on Magento 1.3 version. And when I create in app/code/etc/modules/ the MyPackage_all.xml file, i get this error:

“$string” parameter for simplexml_load_string is empty
Trace:
#0 E:\wamp\www\modas\magento\lib\Varien\Simplexml\Config.php(498): Varien_Simplexml_Config->loadString(”, ‘Mage_Core_Model…’)
#1 E:\wamp\www\modas\magento\app\code\core\Mage\Core\Model\Config.php(177): Varien_Simplexml_Config->loadFile(’E:\wamp\www\mod…’)
#2 E:\wamp\www\modas\magento\app\code\core\Mage\Core\Model\App.php(242): Mage_Core_Model_Config->init(Array)
#3 E:\wamp\www\modas\magento\app\Mage.php(432): Mage_Core_Model_App->init(”, ’store’, Array)
#4 E:\wamp\www\modas\magento\app\Mage.php(453): Mage::app(”, ’store’, Array)
#5 E:\wamp\www\modas\magento\index.php(52): Mage::run()
#6 {main}

Plz help me!

claudio

28. Apr, 2009

Thanks for your tutorial!!

Jeff

08. Jun, 2009

just to see it work i put references to the block into the right, left and content areas of my home page. in the Left and Right sidebars the custom attr showed as “No Custom Attribute Found”, but in the content it came up “Test” as it should have.
I don’t know why.

P.S. i applied the fix to the assignment of getMyCustomer() as seen a few posts above
so ..
if( ( $this->att = $this->getMyCustom() ) && $this->getMyCustom() != ”)

hope this helps

Leave a reply