Joomla Module Tutorial |
Written by dcPages |
Joomla! Modules are probably one of the most important types of extensions for a Joomla! CMS installation. Sure, plugins are nice, but modules actually display something on your website, and they're flexible enough to go just about anywhere. There are lots of modules available all over the web to do all sorts of things, and many of those are free. But what if you want a module to do something on your site and you can't find an existing Joomla! extension that will do it the way you want, or what if you're like me, and you just like doing things yourself, figuring stuff out and just generally getting your hands dirty. Well, don't worry, creating your own Joomla! Module is pretty easy, and this tutorial will guide you through the basics. To create a Joomla! Module, all you really need are a few files in a .ZIP package. This will be accomplished by creating four files:
There are several different "Hello World!" tutorials out there for Joomla! Modules, so for this tutorial, we'll be going a little farther. For the purposes of this discussion, we're going to break apart dcPagesApps PayPal Donate Module. This module is fairly simple, but includes some user-defined parameters so that we can walk through how to set that up as well. This module works by doing the following:
Every Joomla! Module - in fact, every Joomla! Extension, including plugins, modules and components - will begin with an xml file that tells Joomla! about the extension. This will include basic details, like author, extension name, parameters, etc. Let's take a look at the xml file for the PayPal Donate Button Module:
<?xml version="1.0" encoding="utf-8"?>
As you can see, the first half of this just contains some basic info
about the module, like the name, who wrote it, copyright stuff, etc. The
second half is the important part for the sake of this tutorial; that's
where we configure the parameters so that end users can customize the
PayPal button to link to their account and have the correct variables
set for PayPal. Each parameter should contain a name, type (e.g. text,
list, textarea, etc), default value, label, and, optionally, a
description, which pops up as a tip when they hover over the parameter
in the back-end of their site. For "text" type parameters, it's pretty
straighforward, you give it a name, label and default and you're all set
(just remember to close the tag with />, since it's not going to
have any child elements inside it). The "textarea" type - which we used
here for the text to display above the donate button - is similar, but
it takes two additional attributes: 'rows' and 'cols' which specify the
number of rows and columns to display in the text area (those of you
familiar with HTML forms will recognize those attributes from the
<textarea> element). Finally, the "list" type is a select box
(similar to the HTML <select> element). It gets the same
attributes as the others, but also includes a number of child elements.
These elements - the options that the user can select - are added as
p;lt;option> elements in between the opening <param> tag and
before the closing </param> tag for the list element. These
<option> elements need to get a "value" attribute, which sets the
value passed to us by Joomla! if they select that option. They also need
some text in between the opening <option> tag and the closing
</option> tag which is the text that will display for that item in
the select box.<install type="module" version="1.5.0"> <!-- Name of the Module --> <name>PayPal Donate Button</name> <!-- Name of the Author --> <author>dcPagesApps.com - Doug Campbell</author> <!-- Version Date of the Module --> <creationDate>2010-04-11</creationDate> <!-- Copyright information --> <copyright>All rights reserved by dcPagesApps.com.</copyright> <!-- License Information --> <license>GNU/GPL http://www.gnu.org/copyleft/gpl.html</license> <!-- Author's email address --> <authorEmail> info@dcpagesapps.com </authorEmail> <!-- Author's website --> <authorUrl>www.dcpagesapps.com</authorUrl> <!-- Module version number --> <version>1.0.0</version> <!-- Description of what the module does --> <description>Displays a PayPal Donate Button</description> <!-- Listing of all files that should be installed for the module to function --> <files> <!-- The "module" attribute signifies that this is the main controller file --> <filename module="mod_dc_paypal_donate">mod_dc_paypal_donate.php</filename> <filename>index.html</filename> <filename>helper.php</filename> <filename>tmpl/default.php</filename> </files> <!-- Optional parameters --> <params> <param name="business" type="text" default="" label="PayPay ID or Email Address" description="Enter your PayPal Merchant ID or an email address that is linked to your PayPal Account" /> <param name="amount" type="text" default="0" label="Default Donation Amount" description="Enter a default donation, a value of zero (0) will let the user choose their own amount, any other value will only let them donate that amount" /> <param name="no_shipping" type="list" default="" label="Shipping Address Required?" description="Select whether you will require a shipping address"> <option value="0">Optional Shipping Address</option> <option value="1">No Shipping Address</option> <option value="2">Require Shipping Address</option> </param> <param name="return_url" type="text" default="" label="Return URL (successful)" description="Enter the URL where you want people to return to your site, default is your Joomla! front page" /> <param name="return_cancel" type="text" default="" label="Cancel URL (unsuccessful)" description="Enter the URL where you want people who cancel their donations to return to your site, default is your Joomla! front page" /> <param name="cbt" type="text" default="" label="Merchant Name" description="Enter merchant name for use with the 'Return to... [merchant name]' button on the PayPal Site" /> <paran name="donateText" type="textarea" rows="5" cols="30" label="Donation Prompt" default="" description="Text to display above the donate button to entice visitors to donate" /> </params> </install> That does it for the xml file. Next will jump into the main php file for the module. For any Joomla! Module, the main php file (typically called "mod_[module_name].php") is the real brains of the operation. This is the file that will tell the helper php file what to do and it is also the one that will pass our information to the template file. That means that just about every module controller (that's the fancy name for our main php file) will contain something like the following:
// include the helper file
In between those two lines of code, you'll need to include whatever
code you need for your module. In the case of the PayPal button, we just
need to assign our parameters to variables and then we'll pass two of
those variables to the helper so it can check to see if they are good
values. That ends up looking something like this:require_once(dirname(__FILE__).DS.'helper.php'); // include the template for display require(JModuleHelper::getLayoutPath('[module_name_goes_here]'));
// get parameters and insert into item
There are a couple important things to note here. First is how to
assign variables to your template. Basically, your template is passed an
"item" that contains variables the template can use to display
information on the website. You can assign to the "item" using the
syntax above ($item->[variable_name] = someValue). In this case, we
are getting the values to pass the item from our parameters, which bring
us to the next important thing, how to get parameter values. To get a
parameter value, you just need to call the "get()" method of the $params
object. When you call the get() method, you need to include one
argument, which should be the name of a parameter. It's important that
the name of the parameter must match the name of a parameter specified
in your xml file, or else you won't get the information you want
(although, when I tried it with a misspelled parameter name, it didn't
give an error, it just returned an empty variable). The last thing to
notice is how to call a function from your helper file. To do that all
you do is call your module object by name (removing any underscores and
capitalizing the first letter of every word), which in this case is
"ModDcPayPalDonate" and then call the method you want. In this module,
that ends up looking like this:$item->business = $params->get('business'); $item->cbt = $params->get('cbt'); $item->no_shipping = $params->get('no_shipping'); $item->amount = $params->get('amount'); $item->donateText = $params->get('donateText'); // get url data and pass through to helper $return_url = $params->get('return_url'); $item->return_url = ModDcPayPalDonate::getReturnUrl($return_url); $return_cancel = $params->get('return_cancel'); $item->return_cancel = ModDcPayPalDonate::getCancelUrl($return_cancel);
$item->return_url = ModDcPayPalDonate::getReturnUrl($return_url);
When you put this all together, the final module controller file looks like the following:
<!php
//////////////////////////// // Author: dcPagesApps.com - Doug Campbell // Copyright: (C) 2010 - dcPagesApps.com // License: GNU/GPL http://www.gnu.org/copyleft/gpl.html //////////////////////////// //no direct access defined('_JEXEC') or die('Direct Access to this location is not allowed.'); // include the helper file require_once(dirname(__FILE__).DS.'helper.php'); // get parameters and insert into item $item->business = $params->get('business'); $item->cbt = $params->get('cbt'); $item->no_shipping = $params->get('no_shipping'); $item->amount = $params->get('amount'); $item->donateText = $params->get('donateText'); // get url data and pass through to helper $return_url = $params->get('return_url'); $item->return_url = ModDcPayPalDonate::getReturnUrl($return_url); $return_cancel = $params->get('return_cancel'); $item->return_cancel = ModDcPayPalDonate::getCancelUrl($return_cancel); // include the template for display require(JModuleHelper::getLayoutPath('mod_dc_paypal_donate')); ?>
Those of you paying close attention will notice some
extra stuff at the top. The first part is some boiler plate about author
and license that Joomla! likes to see on any extensions listed in their
directory of extensions. The second part prevents people from being
able to call this page directly, which is something you should probably
place in every php file you write unless you specifically need a user to
be able to call that file directly. We'll also do something similar to
protect the folders in our module by adding an index.html file that
tells people that they can't see that folder.
The next piece of this puzzle is the helper file. This is just a php file that contains the functions and methods for your module. By placing them in a separate helper file, you can help to keep your code cleaner. For this PayPal Module, we just need two methods that will check the "Return" and "Cancel" urls that PayPal needs so they can send people back to the correct page if they succeed or cancel. We'll see those in a moment, for right now, let's start with the basic structure of a module helper file.
//no direct access
As you can see, I've already included the no direct access part, but
more important is defining the class for your module. To do that, you
just use the keyword "class" followed by the name of your class.
Technically, you could name it just about anything you want, but to make
sure it plays nicely with Joomla! and the other parts of your module,
you need to use the name of the module (it's also important here that it
matches the name you used in the main php file - in this case
"ModDcPayPalDonate" - so that the main file can talk to the helper
class).defined('_JEXEC') or die('Direct Access to this location is not allowed.'); class [ModNameGoesHere] { [some code here] } Next we need to create the methods to check the cancel and return urls. For the purposes of this discussion, we're just going to see if the user supplied a url, and if not, then get the default url for the website. That will look something like this:
// check to see if we have a URL, if not, use the base from the website
These two php functions are pretty straight forward. It takes the url
passed to it from the main php file. If that value has zero length
(i.e. if it's an empty string), then it assigns the url from the main
page of the website by calling the base() method of the JURI object.
Then it returns the final url to the main php file. Once we add those to
the standard structure, our final helper.php looks like this:public function getReturnUrl($strUrl){ if(strlen($strUrl)==0){ $strUrl = JURI::base(); } return $strUrl; } // check to see if we have a URL, if not, use the base from the website public function getCancelUrl($strUrl){ if(strlen($strUlr)==0){ $strUrl = JURI::base(); } return $strUrl; }
<?php
That's it for the helper.php file. All we need to do now is create a default template. We'll do that on the next page.//////////////////////////// // Author: dcPagesApps.com - Doug Campbell // Copyright: (C) 2010 - dcPagesApps.com // License: GNU/GPL http://www.gnu.org/copyleft/gpl.html //////////////////////////// //no direct access defined('_JEXEC') or die('Direct Access to this location is not allowed.'); class ModDcPayPalDonate { // check to see if we have a URL, if not, use the base from the website public function getReturnUrl($strUrl){ if(strlen($strUrl)==0){ $strUrl = JURI::base(); } return $strUrl; } // check to see if we have a URL, if not, use the base from the website public function getCancelUrl($strUrl){ if(strlen($strUlr)==0){ $strUrl = JURI::base(); } return $strUrl; } } // end of ModDcPayPalDonate ?> The final piece of the Joomla! Module puzzle is the template, which Joomla! uses to actually display content to the user. Technically, the template file could be just static information. If you wanted to make a module that never changed and didn't allow the user to customize it, you could just put the static content into the template and you're done. However, in most cases - and definitely in the case of the PayPal Donate Button Module - your template will need to be able to produce dynamic content. In this case, we're going to be creating a PayPal Donate Button. So let's start by taking a look at the html code for the PayPal Button as provided by PayPal (you can get this code by logging into your PayPal account and creating a button using their code generator in your profile). The code looks like this:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
Now this form will work, but it will only let people donate to
dcPagesApps, since that's the value set for the variable "business". In
order to make this work for other users, we need to have those values
pulled from the $item that we created in our module controller php file.
To do that, all we do is use a php 'echo' command to give us the values
we want, which ends up looking like this:<input type="hidden" name="cmd" value="_donations"> <!-- set parameters --> <input type="hidden" name="business" value=" paypal@dcpagesapps.com " /> <input type="hidden" name="no_shipping" value="1" /> <input type="hidden" name="cbt" value="dcPagesApps.com" /> <input type="hidden" name="return_url" value="http://www.dcpagesapps.com" /> <input type="hidden" name="return_cancel" value="http://www.dcpagesapps.com/" /> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
Now we're almost done, our module has two other variables that we
will need to deal with: donate text and default amount. Since these
variables are optional, we need to check if they are populated and then
have the template insert something if they are, which looks like this:<input type="hidden" name="cmd" value="_donations"> <!-- set parameters --> <input type="hidden" name="business" value="<?php echo $item->business; ?>" /> <input type="hidden" name="<?php echo $item->no_shipping; ?>" value="1" /> <input type="hidden" name="cbt" value="<?php echo $item->cbt; ?>" /> <input type="hidden" name="return_url" value="<?php echo $item->return_url; ?>" /> <input type="hidden" name="return_cancel" value="<?php echo $item->return_cancel; ?>" /> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form>
if(strlen($item->donateText)>0) {
andecho "<div class='donateText'>"; echo $item->donateText; echo "</div>"; } // end donateText conditional
<?php
So now all we have to do is put those in the correct places for our
template. Which puts the donate text above the form and the default
amount inside the form. This means our final code will look like this:// check to see if we have a default value greater than 0 if($item->amount > 0){ ?> <input type="hidden" name="amount" value="<?php echo $item->amount; ?>" /> <?php } ?>
if(strlen($item->donateText)>0) {
That's it for the template file, now all we have to do is package the module and we're done.echo "<div class='donateText'>"; echo $item->donateText; echo "</div>"; } // end donateText conditional <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_donations"> <!-- set parameters --> <input type="hidden" name="business" value="<?php echo $item->business; ?>" /> <input type="hidden" name="<?php echo $item->no_shipping; ?>" value="1" /> <input type="hidden" name="cbt" value="<?php echo $item->cbt; ?>" /> <input type="hidden" name="return_url" value="<?php echo $item->return_url; ?>" /> <input type="hidden" name="return_cancel" value="<?php echo $item->return_cancel; ?>" /> <?php // check to see if we have a default value greater than 0 if($item->amount > 0){ ?> <input type="hidden" name="amount" value="<?php echo $item->amount; ?>" /> <?php } ?> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> By now, you should have four files:
In order to make this a fully functional Joomla! Extension, you just need to put all of those into a single .zip package. There are plenty of great programs to do this, like WinRar for example, but even if you don't have a special program for it, both Windows and Mac now have this functionality built in. For Windows, just right-click on the folder that contains your module files and click on "Send To" then "Compressed Folder" and Windows will put that folder's contents into a .zip file for you. To install the module, just login to your Joomla! Administrator section, and click on the "Extensions" menu and select "Install/Uninstall". Then browse to your new .zip file and install it. You'll also want to go to the module manager (click "Extensions" and then "Modules") and click "New" to add this module to your site and configure the variables so that the button links up with your PayPal Account. I hope you've enjoyed this tutorial. If you have any questions, comments, suggestions or complains, don't hesitate to send me an email - info@dcpagesapps.com - or just post a comment below. Also, if you've found this tutorial informative, consider donating using the button on your left. Thanks, -dcPages |
No comments:
Post a Comment