Home > Articles > Web Development

This chapter is from the book

This chapter is from the book

Improved User Registration Plugin

In the previous example, we created the myregistration plugin to add validation to the alternative user registration menu item we created in Chapter 4. This plugin depends on this alternative menu item. To transfer this functionality to another Joomla website, we would have to install the alternative menu item—including the beez_20_copy template—as well as the new myregistration plugin. It would be easier to manage if we could do the entire job in the plugin.

Using the new JForm class and the form event added in Joomla version 1.6, we can override the registration form inside the plugin, without creating a separate alternative Menu Item file. We can also use JForm to do the validation for us, and thereby eliminate the need for the onBeforeSave() plugin method. With this approach, we can package all this functionality into one small plugin extension and make it very easy to add this capability to another Joomla website.

We’ll call this version of the plugin myregistration2. It will contain the following files:

  • forms/form.xml: File with the JForm information for the fields added by the plugin
  • language/en-GB/en-GB.plg_user_myregistration2.ini: Main language file
  • language/en-GB/en-GB.plg_user_myregistration2.sys.ini: Sys language file
  • myregistration2.php: Plugin code file
  • myregistration2.xml: Plugin XML file

Let’s go through the steps to create the plugin.

Create the Plugin XML File

As before, we create the plugin folder (plugins/user/myregistration2) and create our main XML file in that folder. The listing for the myregistration2.xml file is shown in Listing 5.7.

Listing 5.7. myregistration2.xml File

<?xml version="1.0" encoding="utf-8"?>
<extension version="2.5" type="plugin" group="user" method="upgrade" >
    <name>plg_user_myregistration2</name>
    <author>Mark Dexter and Louis Landry</author>
    <creationDate>January 2012</creationDate>
    <copyright>(C) 2012 Mark Dexter and Louis Landry. All rights reserved.
    </copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt
    </license>
    <authorEmail>admin@joomla.org</authorEmail>
    <authorUrl>www.joomla.org</authorUrl>
    <version>2.5.0</version>
    <description>PLG_USER_MYREGISTRATION2_XML_DESCRIPTION</description>

    <files>
         <filename plugin="myregistration2">myregistration2.php</filename>
         <filename>index.html</filename>
         <folder>forms</folder>
         <folder>language</folder>
    </files>

    <config>
    </config>
</extension>

This file is similar to the previous example. Note that we change the name of the plugin in the name element and twice in the filename element. Also, we have added a folder element for the form folder. We discuss that in the next section.

Create the Form XML File

In this example, we use the JForm class to add our two fields to the registration form. With JForm, we can add fields to a form using one of two techniques:

  • Load the fields from an XML file.
  • Load the fields from a string (for example, created inside the plugin PHP file).

The first method is recommended for most cases, since it is generally easier to work with and maintain an XML file. Listing 5.8 shows the code for the form.xml file.

Listing 5.8. form.xml File

<?xml version="1.0" encoding="utf-8"?>
<form>
    <fieldset name="tos"
        label="PLG_USER_MYREGISTRATION2_TERMS_OF_SERVICE"
    >
        <field name="tos_agree" type="checkbox"
            default="0"
            filter="bool"
            label="PLG_USER_MYREGISTRATION2_AGREE"
            required="true"
            value="1"
        />

        <field name="old_enough" type="checkbox"
            default="0"
            filter="bool"
            label="PLG_USER_MYREGISTRATION2_AGE"
            required="true"
            value="1"
        />
    </fieldset>
</form>

This file defines the two fields we want to add to the user registration form, and it closely mirrors the actual HTML code that will be created by JForm. The outer element is called form and will create an HTML form element. It contains one fieldset element. A fieldset HTML element is used to group fields together on the form. Inside the fieldset, we have our two field elements.

Each field element has the following attributes:

  • default: Default value (if unchecked)
  • filter: The filter used to check the input from this field
  • label: The label for this field (note that this will be translated)
  • required: Flag to tell JForm to make this field required
  • value: The value in the form when the checkbox is checked

The label and value attributes are standard attributes of the HTML input element. The filter attribute causes JForm to filter the input field using one of the standard JHtml filter values. In this case, we are filtering to allow only boolean true and false values. So even if a user changes the form in their browser to submit some other information (for example, some malicious SQL or JavaScript code), JForm will filter this and convert it to a boolean value.

The default attribute specifies the value to send if this input is not entered—in this case, if the check box is not checked. We specify a value of “0,” which will convert to a boolean false.

The required attribute causes JForm to require this input field to be filled out. In the case of a check box, this requires that the check box is checked. JForm will not allow the user to register without checking the box. Because JForm handles this validation automatically, we don’t need the onBeforeSave() method that we used in the myregistration plugin.

We see how this file is used in the next section.

Create the Plugin PHP File

Listing 5.9 shows the code for the myregistration2.php file.

Listing 5.9. myregistration2.php File

<?php
/**
* @copyright  Copyright (C) 2012 Mark Dexter and Louis Landry
* @license  GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('JPATH_BASE') or die;
/**
 * This is our custom registration plugin class.  It verifies that the user checked the boxes
 * indicating that he/she agrees to the terms of service and is old enough to use the site.
 *
 * @package     Joomla.Plugins
 * @subpackage  User.MyRegistration2
 * @since       1.0
 */
class plgUserMyRegistration2 extends JPlugin
{

    /**
     * Method to handle the "onContentPrepareForm" event and alter the user registration form.  We
     * are going to check and make sure that the form being prepared is the user registration form
     * from the com_users component first.  If that is the form we are preparing, then we will
     * load our custom xml file into the form object which adds our custom fields.
     *
     * @param   JForm  $form  The form to be altered.
     * @param   array  $data  The associated data for the form.
     *
     * @return  bool
     *
     * @since   1.0
     */
    public function onContentPrepareForm($form, $data)
    {
         // If we aren't in the registration form ignore the form.
         if ($form->getName() != 'com_users.registration') {
            return;
         }

         // Load the plugin language file
         $this->loadLanguage();

         // Load our custom registration xml into the user registration form.
         $form->loadFile(dirname(__FILE__).'/forms/form.xml');
    }

}

The first part is the same as the earlier plugins. We rely on the autoloader to import the JPlugin class, and we extend that class. We name the plugin class according to the plugin naming convention—in this case, plgUserMyRegistration2.

The class has one method, onContentPrepareForm(). The onContentPrepareForm event is triggered at the point where the JForm has been prepared but not yet rendered. We are able to modify the JForm object in working memory just before it is used to create the form. Two arguments are passed to the class. The variable $form holds the JForm object and the variable $data holds a standard object with any data for the form.

Then we make sure we are processing a registration form. If we are not (meaning that we are processing some other form), we just want to quit. So we test the form name. If it is not equal to com_users.registration, we return without doing any processing.

At this point, we know we are processing the user registration form. Next we load the language file so we can translate the language text in our form.

Then the last line does all the work to create the two new fields. It calls the loadFile() method of JForm with our form.xml file as the argument. This causes JForm to merge the fields in the form.xml file with the form that is already in working memory from the standard XML file (in this case, components/com_users/models/forms/registration.xml). Since the two fields in our form.xml file are new fields (in other words, they have different names from those of the other fields in the form), the two new fields are added to the form.

That’s all there is to it. At this point, the fields in our form.xml file have been added to the form and will be included in the output. As mentioned earlier, because we use the required attribute in the fields, we don’t need additional code to ensure that these boxes are checked. JForm does it for us.

Add the Language Files

As before, we have two language files, located in the folder plugins/user/myregistration2/language/en-GB). The main file is en-GB.plg_user_myregistration2.ini. The .sys file is used for translating the plugin name and description in the plugin manager. These are shown in Listing 5.10 and Listing 5.11.

Listing 5.10. en-GB.plg_user_myregistration2.ini File

; Language file for myregistration2 plugin

PLG_USER_MYREGISTRATION2_TERMS_OF_SERVICE="Added Fields for Terms of Service Agreement"
PLG_USER_MYREGISTRATION2_AGREE="I agree to the terms."
PLG_USER_MYREGISTRATION2_AGE="I am at least 18 years old."

Listing 5.11. en-GB.plg_user_myregistration2.sys.ini File

; sys language file for myregistration2 plugin
; The .sys.ini files are used when listing the extensions in the extension manager or plugin manager

PLG_USER_MYREGISTRATION2="User - My Registration2"
PLG_USER_MYREGISTRATION2_XML_DESCRIPTION="Demonstration plugin that checks that overrides user registration. Checks that terms and age boxes have been checked."

Test the Plugin

Test the plugin as we have done in the previous examples, using the Extension Manager Discover and Install functions.

To test the plugin, you will need to disable the myregistration plugin (not the myregistration2 plugin), enable the myregistration2 plugin, and make sure that the Registration menu item uses the default menu item type instead of the alternative menu item type (Register With Approval) that we created in Chapter 4.

Once this is set up, when you load the Registration menu item, you should see the form shown in Figure 5.6.

Figure 5.6

Figure 5.6. Custom registration form from MyRegistration2 plugin

Notice that the two new fields show the asterisk to indicate they are required, just like the other required fields on the form. If you press the Register button without checking the check boxes, you should see the following messages:

Figure 5.7

Figure 5.7. JForm required field messages

These are the standard messages that JForm shows when the user submits a form that is missing required fields.

Package the Plugin

To package the plugin for installation from an archive file, we follow the same process as described earlier:

  1. Copy the files from the plugins/user/myregistration2 folder to a temporary folder on your computer.
  2. Use an archive program to create a zip archive of these files. By convention, the archive would be called plg_user_myregistration2.zip (but it can be named anything as long as it contains all the correct files and folders).

Test that the archive file can be installed successfully by uninstalling the existing myregistration2 plugin and then installing it from the archive file.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020