Thursday, November 8, 2012

j25: joomla function

JRequest::getVar()
$address = JRequest::getVar('address');  -data only 
$address = JRequest::getVar('address', 'Address is empty'); -default param
$address = JRequest::getVar('address', 'default value goes here', 'post'); - source param
 
$address = JRequest::getVar('address', 'default value goes here', 'post','validation type',mask type);
 
validation type (INT,INTEGER,FLOAT,DOUBLE,BOOL,BOOLEAN,WORD,ALNUM,CMD,BASE64,STRING,ARRAY,PATH,USERNAME)
mask type :
 - JREQUEST_NOTRIM - prevents trimming of whitespace
 - JREQUEST_ALLOWRAW - bypasses filtering
 - JREQUEST_ALLOWHTML - allows most HTML. If this is not passed in, HTML is stripped out by default.
 
JRequest::get( 'post' )
To receive a whole array filtered. If you would want to get the POST data 

j25 : Template

Section 1:
_JEXEC is a variable defined in Joomla's main index.php file. When you check if the variable has been defined yet, you can learn whether a file is being accessed directly or is being included as it should.
Section 2:
The $showRightColumn variable has a 1 or 0 value. If there are no modules being loaded in the right column, it has a value of 0, or false. Likewise, if modules are being loaded, it has a value of 1, or true.
Section 3:
The $this-countModules() function returns the total number of active modules for the given position. In this tutorial, we'll show you how it works.
Section 4:
When using $this-params-get() in a Joomla 2.5 template file, you can call the value of a parameter set by the user for the template. For example, if your template allows the user to enter the background color of the template, using $this-params-get you can grab the color the user entered.
Section 5:
While JFactory::getApplication() can be used in many different ways, it appears it is only used in the Beez2 template to get the value of the site's title and description (which are Advanced Options) for the template.
Section 6:
In the Beez2 template, JFactory::getDocument is called in order to tell Joomla to include an additional javascript file in the page.
Section 7:
The $this variable is used quite often in the Beez2 Joomla 2.5 template, and it references the JDocumentHTML Object.
Section 8:
In this tutorial, we'll show you how to use the $this-baseurl variable within a Joomla template to reference your site's URL.
Section 9:
$this-template in a Joomla 2.5 template can be used to get the folder name of the current template, which is helpful for dynamically creating URLs to css and other files.
Section 10:
The $this-language variable in Joomla 2.5 can be used to reference the current language being used, such as en-gb or es-es.
Section 11:
$this-direction in a Joomla 2.5 template gives you access to the direction text has been set to (for example ltr - left to right).
Section 12:
In the following Joomla 2.5 template tutorial, we'll show you how to add a new position to your template.
Section 13:
$files = JHtml::_(stylesheet) is used in our Joomla 2.5 template's index.php file as a method of loading a css file, general.css

Wednesday, October 31, 2012

j2.5 : Membina modul untuk Joomla 1.7 - 3.0



1. Struktur fail modul untuk joomla 1.7 - 3.0

/modules/mod_plogin/mod_plogin.xml
/modules/mod_plogin/mod_plogin.php
/modules/mod_plogin/helper.php
/modules/mod_plogin/index.html
/modules/mod_plogin/tmpl/default.php
/modules/mod_plogin/tmpl/index.html

File yang mula2 dibaca untuk sesuatu modul adalah fail sambungan php yang sama dengan nama "folder", cth mod_plogin

/modules/mod_plogin/mod_plogin.php - fail yang mula2 dibaca untuk satu2 module
/modules/mod_plogin/helper.php - syndicate functions only once, include in mod_plogin

2.

Tuesday, October 23, 2012

j1.6 Creating a custom form field type

Creating a custom form field type

(Redirected from Overriding JFormFields)
Jump to: navigation, search
JForm, a feature introduced in Joomla 1.6, lets you easily create HTML forms (<form>). Forms created using JForm consist of form fields, implemented as JFormFields. There is a JFormField for each different field type you can find in a form, such as a text field type and a date field type. JForm supports a large selection of standard field types. For a full list, see Standard form field types.
Joomla 1.6 makes it possible to extend standard field types or define your own. For example, if your component manages phone book entries, you might want to define a form field type that outputs a select list of cities. There are several advantages to defining a custom form field type:
  • You will be able to mix standard field types with your custom field type in a JForm-based form.
  • You will eventually have a reusable code package that can be used easily throughout your code.
  • Extensions that collaborate with your extension will be able to create form fields without meddling with your database tables and other internals.

Contents

 [hide

Form field type class requirements

A form field type is defined in a class that must be a (not necessarily direct) subclass of JFormField. To work correctly, the class must define at least two methods:
  • public function getLabel()
    This function will be called to create the label that belongs to your field and must return a HTML string containing it. Since JFormField defines a ready-to-use getLabel() implementation, custom form field types usually do not define their own getLabel(). If you leave it out, the inherited method of creating labels will be used. It is recommended to leave out the getLabel() method for consistency and speed unless you actually want to modify the label's HTML.
  • public function getInput()
    This function will be called to create the field itself and must return a HTML string containing it. This is also where most of the processing usually happens. In our phone book City field example, this function will have to retrieve a list of available cities and return a HTML <select> with the cities inserted as <option>s.
Inside your code, you will have to process the attributes set by the field's user in the XML form definition. Some of those attributes are accessible via protected member variables of JFormField. For example, the name attribute is available in your code as $this->name. Similarly, label, description, default, multiple and class are also available as properties of $this. Other parameters you might have defined can be accessed through the $this->element array: the attribute size will be in $this->element['size'].

Which class to subclass?

For a form field type to be usable in JForm, it needs do be a subclass of JFormField. However, it does not have to be a direct child of that class: you can also subclass an existing (standard or custom) form field type and thereby inherit useful code.
If your form field type is quite similar to an existing type, you should subclass that type. Especially if your form field type is a list, please subclass JFormFieldList. You only have to override getOptions() method to return the options to be shown; the getInput() method will convert those options to HTML.
To subclass an existing type, for example JFormFieldList, load it by adding the following to after jimport('joomla.form.formfield');:
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
If your form field type is unlike any existing type, subclass JFormField directly.

Location of files

  • The standard form field types are located in joomla/libraries/joomla/form/fields/. You should not store custom fields there, nor should you have to use this path in your own code, but the standard types are usually good examples.
  • The custom field types that belong to your component are usually located in administrator/components/<name of your component>/models/fields. You can specify this or another path in your code:
JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
  • The XML files that define forms are usually located in administrator/components/<name of your component>/models/forms. Use something like the following snippet to specify a path to your forms:
JForm::addFormPath(JPATH_COMPONENT . '/models/forms');

Naming conventions and skeleton

In this section, <ComponentName> represents the camel-cased name of your component and <TypeName> represents the camel-cased name of your form field type. The field's class should be placed in administrator/components/<name of your component>/models/fields/<name of your field>.php, and look like this:
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
 
jimport('joomla.form.formfield');
 
// The class name must always be the same as the filename (in camel case)
class JFormField<FieldName> extends JFormField {
 
        //The field class must know its own type through the variable $type.
        protected $type = '<FieldName>';
 
        public function getLabel() {
                // code that returns HTML that will be shown as the label
        }
 
        public function getInput() {
                // code that returns HTML that will be shown as the form field
        }
}

Grouping custom field types

Warning: this information is partially incorrect and needs to be improved.
Custom field types can be grouped by using an underscore in the field name. A field class with a name for example like "JFormFieldMy_randomField" must be stored in administrator/components/<name of your component>/models/fields/my/randomField.php. We can prefix our form field names with some group name, then we put an underscore and then a name of a field.

An example custom field type

Suppose you're working on your component named com_phonebook and you want to define a field that contains cities. Create the file administrator/components/com_phonebook/models/fields/city.php and write something similar to the following:
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
 
jimport('joomla.form.formfield');
 
class JFormFieldCity extends JFormField {
 
        protected $type = 'City';
 
        // getLabel() left out
 
        public function getInput() {
                return '<select id="'.$this->id.'" name="'.$this->name.'">'.
                       '<option value="1" >New York</option>'.
                       '<option value="2" >Chicago</option>'.
                       '<option value="3" >San Francisco</option>'.
                       '</select>';
        }
}

Using the custom field type

To use the field type City, we need to update the XML file that contains the form fields. Open your XML file located in administrator/components/com_phonebook/models/forms and add the field in the usual way:
<field name="title" type="City" label="JGLOBAL_TITLE"
        description="JFIELD_TITLE_DESC"
        required="true" />
The type name is cAsE-sEnSiTiVe.

In addition, you may need to add the field path to the parent <fieldset>:
<fieldset addfieldpath="/administrator/components/<component name>/models/fields">

Overriding getLabel()

As mentioned in the section Form field type class requirements, custom form field types usually do not define their own getLabel(). If you do want to create a custom label, you can still make use of the getLabel() that every field type class inherits from JFormField, for example by defining it as follows:
public function getLabel() {
     return '<span style="text-decoration: underline;">' . parent::getLabel() . '</span>';
}
This code will underline your form labels. (Please note that if your goal is to underline form labels, using CSS is the preferred way.)
If you want to do something completely different, you can of course also override it completely:
public function getLabel() {
        // Initialize variables.
        $label = '';
        $replace = '';
 
        // Get the label text from the XML element, defaulting to the element name.
        $text = $this->element['label'] ? (string) $this->element['label'] : (string) $this->element['name'];
 
        // Build the class for the label.
        $class = !empty($this->description) ? 'hasTip' : '';
        $class = $this->required == true ? $class.' required' : $class;
 
        // Add replace checkbox
        $replace = '<input type="checkbox" name="update['.$this->name.']" value="1" />';
 
        // Add the opening label tag and main attributes attributes.
        $label .= '<label id="'.$this->id.'-lbl" for="'.$this->id.'" class="'.$class.'"';
 
        // If a description is specified, use it to build a tooltip.
        if (!empty($this->description)) {
                $label .= ' title="'.htmlspecialchars(trim(JText::_($text), ':').'::' .
                                JText::_($this->description), ENT_COMPAT, 'UTF-8').'"';
        }
 
        // Add the label text and closing tag.
        $label .= '>'.$replace.JText::_($text).'</label>';
 
        return $label; 
}
This example will add a checkbox before the label.

How to change the module output in Joomla

How to change the module output in Joomla

Thursday, 26 January 2012 14:10
In Joomla, the module output is controlled through the Module Chrome and the file templates/system/html/modules.php. When you insert a module position inside your template index.php file, you usually define a style for it.
For example:
1.<jdoc:include type="modules" name="user1" style="xhtml" />
In the above example the style you have defined is xhtml. This means that Joomla will look into the file templates/system/html/modules.php to find the Module Chrome modChrome_xhtml. This Module Chrome defines the module output structure.

However you can override this Module Chrome if there is a file modules.php inside templates/your_template/html/. In this file you can redefine a Module Chrome modChrome_xhtml so that you can override the default one in templates/system/html/modules.php.

You can also create a new custom Module Chrome. For example let's create a new Module Chrome with the name minitek. In this case the module include inside the file index.php of your template should be:
1.<jdoc:include type="modules" name="user1" style="minitek" />
The module style in the above example is minitek. Now we must define a Module Chrome modChrome_minitek inside the file modules.php.

Open the file templates/your_template/html/ and insert this new function: (Create this file if it does not exist)
01.<?php
02.// no direct access
03.defined('_JEXEC') or die('Restricted access');
04. 
05. 
06.function modChrome_minitek($module, &$params, &$attribs)
07.{
08.if (!empty ($module->content)) : ?>
09.<div class="moduletable<?php echo $params->get('moduleclass_sfx'); ?>">
10.<?php if ($module->showtitle != 0) : ?>
11.<h3><?php echo $module->title; ?></h3>
12.<?php endif; ?>
13.<?php echo $module->content; ?>
14.</div>
15.<?php endif;
16.}
You see that the function name is modChrome_minitek because we have defined the style minitek in the module include.
Now you can customize the above code, for example you can change the ordering of the html elements or add new ones. You can change the h3 tag to a h2 for example or make any customizations you like.




Related items (by tag)

Thursday, October 18, 2012

Joomla Module Tutorial

Joomla Module Tutorial PDF Print E-mail
Written by dcPages   
Article Index
Joomla Module Tutorial
Joomla! Module Tutorial - Page 2
Joomla! Module Tutorial - Page 3
Joomla! Module Tutorial - Page 4
Joomla! Module Tutorial - Page 5
Joomla! Module Tutorial - Page 6
All Pages
&am
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:
  • helper.php - the helper file for the module
  • mod_[module_name].php - the php file that runs the module
  • mod_[module_name].xml - the xml file that tells Joomla! the details of your module
  • tmpl\default.php - the template file for your module (located in a folder called 'tmpl')
Technically, you could get this done without needed the helper or template file, but that will severly limit your code, and including those files is a standard coding practice for Joomla!, so if you want to list your module in the Joomla! Extensions Directory, then you will need to include them.
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:
  • Get parameter values
  • Check parameter values and update if necessary
  • Pass that info to the template
It's really very easy so let's dive in.

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"?>
<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>
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.
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
require_once(dirname(__FILE__).DS.'helper.php');

// include the template for display
require(JModuleHelper::getLayoutPath('[module_name_goes_here]'));
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:
// 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);
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->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
defined('_JEXEC') or die('Direct Access to this location is not allowed.');

class [ModNameGoesHere]
{
[some code here]
}
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).
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
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;
}
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:
<?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.');

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

?>
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.

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">
<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>
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:
<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; ?>" />


<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>
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:
if(strlen($item->donateText)>0) {

echo "<div class='donateText'>";
echo $item->donateText;
echo "</div>";

} // end donateText conditional
and
<?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
}
?>
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:
if(strlen($item->donateText)>0) {

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>
That's it for the template file, now all we have to do is package the module and we're done.



By now, you should have four files:

  • mod_dc_paypal_donate.xml
  • mod_dc_paypal_donate.php
  • helper.php
  • default.php (in a subfolder called "tmpl")

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

J1.7 : How to create a database driven Joomla module

How to create a database driven Joomla module

Wednesday, 03 August 2011 12:46 In this tutorial we will create a fresh new module for Joomla 1.7 that is driven by a MySQL database.
The process is very fast and easy and if you follow the guidelines below you will get the hang of it very quickly.

The features:

In this module we will use the table jos_users to retrieve the id, name and username of the registered users.

In the module parameters we will be able to control the user data we want to display.

Step 1

The file structure


Create the file structure that you see below, using your favorite file editor.
Tip: I am using a great free text / code editor called HTML-Kit. You can download it for free here.
1.mod_userdata.xml
2.mod_userdata.php
3.helper.php
4.index.html
5.tmpl/default.php
6.tmpl/index.html
This is the most basic file structure for a database driven module.

Step 2

The files


Now let's populate our files.
1. Open the file mod_userdata.xml and insert this code
01.<?xml version="1.0" encoding="UTF-8"?>
02.<extension type="module" version="1.7" client="site" method="upgrade">
03.<name>User Data Module</name>
04.<author>Minitek.gr</author>
05.<creationDate>03/08/2011</creationDate>
06.<copyright>Copyright (C) 2011. All rights reserved.</copyright>
07.<license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL</license>
08.<authorEmail>your_email</authorEmail>
09.<authorUrl>www.minitek.gr</authorUrl>
10.<version>1.7.1</version>
11.<description>Users Data Module</description>
12.<languages>
13.</languages>
14.<files>
15.<filename module="mod_userdata">mod_userdata.php</filename>
16.<filename>mod_userdata.xml</filename>
17.<filename>helper.php</filename>
18.<filename>index.html</filename>
19.<folder>tmpl</folder>
20.</files>
21.<config>
22.<fields name="params">
23.<fieldset name="basic">
24.<field name="moduleclass_sfx" type="text" default="" label="Module Class Suffix" description="Suffix for individual css styling" />
25.<field name="limit" type="text" default="10" label="Limit Displayed Users" description="Limit Displayed Users" />
26.<field name="user_id" type="radio" default="1" label="Display user ID" description="Display user ID">
27.<option value="0">JNO</option>
28.<option value="1">JYES</option>
29.</field>
30.<field name="user_name" type="radio" default="1" label="Display Name" description="Display Name">
31.<option value="0">JNO</option>
32.<option value="1">JYES</option>
33.</field>
34.<field name="user_username" type="radio" default="1" label="Display Username" description="Display Username">
35.<option value="0">JNO</option>
36.<option value="1">JYES</option>
37.</field>
38.</fieldset>
39.</fields>
40.</config>
41.</extension>
This is the typical structure of a module xml file for Joomla 1.7.

2. Open the file mod_userdata.php and insert this code
01.<?php
02./**
03.* @package Joomla.Site
04.* @subpackage  mod_userdata
05.* @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
06.* @license GNU General Public License version 2 or later; see LICENSE.txt
07.*/
08. 
09.// no direct access
10.defined('_JEXEC') or die;
11. 
12.// Include the syndicate functions only once
13.require_once dirname(__FILE__).'/helper.php';
14. 
15.// Get the user data
16.$list   = modUserDataHelper::getData($params);
17. 
18.// Get the layout
19.require JModuleHelper::getLayoutPath('mod_userdata', $params->get('layout', 'default'));
3. Now let's move on to the file helper.php. This is the file that retrieves the data from the MySQL table.
Open the file helper.php and insert this code
01.<?php
02./**
03.* @package     Joomla.Site
04.* @subpackage  mod_userdata
05.* @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
06.* @license     GNU General Public License version 2 or later; see LICENSE.txt
07.*/
08. 
09.// no direct access
10.defined('_JEXEC') or die;
11. 
12.class modUserDataHelper
13.{
14.function getData( &$params )
15.{
16. 
17.// Database query       
18.$list = array();        
19.$query = " SELECT id, name, username "              
20.." FROM #__users "
21.." WHERE block=0 "              
22.." ORDER BY id DESC "
23.." LIMIT " . $params->get( 'limit' );            
24.$db =& JFactory::getDBO();
25.$db->setQuery( $query );     
26.$rows = $db->loadObjectList();
27. 
28.// Get list items
29.if ($rows!=null)
30.{
31.$i=0;
32.foreach ($rows as $row)
33.{              
34.$list["users"][$i]["id"]=$row->id;
35.$list["users"][$i]["name"]=$row->name;
36.$list["users"][$i]["username"]=$row->username;
37.$i++;     
38.}
39.return $list;
40.}
41. 
42.}
43.}
In this file, we firstly request the id, name and username from the table jos_users where the users are not blocked (block=0). Then we order the results by id and finally we limit the results to the limit that is defined in the module backend parameters. Let's move on to our template file.

4. Our template file is responsible for displaying the results.
Open the file tmpl/default.php and insert this code
01.<?php
02./**
03.* @package     Joomla.Site
04.* @subpackage  mod_userdata
05.* @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
06.* @license     GNU General Public License version 2 or later; see LICENSE.txt
07.*/
08. 
09.// no direct access
10.defined('_JEXEC') or die; ?>
11. 
12.<div class="moduletable<?php echo $params->get( 'moduleclass_sfx' ) ?>">
13. 
14.<ul>
15.<?php for ($i=0;$i< sizeof($list["users"]); $i++) { ?>  
16. 
17.<li>
18.<?php if ($params->get( 'user_id' )) { ?>
19.<span><?php echo $list["users"][$i]["id"];?></span>
20.<?php } ?>
21.<?php if ($params->get( 'user_name' )) { ?>
22.<span><?php echo $list["users"][$i]["name"];?></span>
23.<?php } ?>
24.<?php if ($params->get( 'user_username' )) { ?>
25.<span><?php echo $list["users"][$i]["username"];?></span>
26.<?php } ?>
27.</li>
28. 
29.<?php } ?>
30.</ul>
31. 
32.</div>
5. Open the file index.html as well as the file tmpl/index.html and insert this code
1.<html><body bgcolor="#FFFFFF"></body></html>
This will prevent unauthorized directory browsing.
Now we are ready to pack our files and install the new module.

Step 3

Let's pack the files and install


Zip all the files we created in an archive called mod_userdata.zip. Now go to Joomla Administration -> Extension Manager and install the package. When the installation is complete, go to Module Manager, open the module, enable it and configure the parameters.
Go to frontend and check out what you have created! Have fun!