Adding Features to your Joomla! Form using ChronoForms

Exclusive offer: get 50% off this eBook here
ChronoForms 3.1 for Joomla! site Cookbook

ChronoForms 3.1 for Joomla! site Cookbook — Save 50%

80 recipes for building attractive and interactive Joomla! forms

$26.99    $13.50
by Bob Janes | August 2010 | Joomla! Content Management Open Source Web Development

Joomla! is a fantastic way to create a dynamic CMS. Now, you want to go to the next step and interact with your users. Forms are the way you ask questions and get replies. ChronoForms is the extension that lets you do that and this article tells you how.

In this article by Bob Janes, author of the book ChronoForms 3.1 for Joomla! site Cookbook , we will cover:

  • Adding a validated checkbox
  • Adding an "other" box to a drop-down
  • Sending an SMS message on submission
  • Signing up to a newsletter service
  • Adding a conversion-tracking script

(For more resources on ChronoForms, see here.)

Introduction

We have so far mostly worked with fairly standard forms where the user is shown some inputs, enters some data, and the results are e-mailed and/or saved to a database table. Many forms are just like this, and some have other features added. These features can be of many different kinds and the recipes in this article are correspondingly a mixture.

Some, like Adding a validated checkbox, change the way the form works. Others, like Signing up to a newsletter service change what happens after the form is submitted.

While you can use these recipes as they are presented, they are just as useful as suggestions for ways to use ChronoForms to solve a wide range of user interactions on your site.

Adding a validated checkbox

Checkboxes are less often used on forms than most of the other elements and they have some slightly unusual behavior that we need to manage. ChronoForms will do a little to help us, but not everything that we need.

In this recipe, we'll look at one of the most common applications—a stand alone checkbox that the user is asked to click to ensure that they've accepted some terms and conditions. We want to make sure that the form is not submitted unless the box is checked.

Getting ready

We'll just add one more element to our basic newsletter form. It's probably going to be best to recreate a new version of the form using the Form Wizard to make sure that we have a clean starting point.

How to do it...

  1. In the Form Wizard, create a new form with two TextBox elements. In the Properties box, add the Labels "Name" and "Email" and the Field Names "name" and "email" respectively.
  2. Now drag in a CheckBox element.
  3. You'll see that ChronoForms inserts the element with three checkboxes and we only need one. In the Properties box remove the default values and type in "I agree".

    While you are there change the label to "Terms and Conditions".

    Lastly, we want to make sure that this box is checked so check the Validation | One Required checkbox and add "please confirm your agreement" in the Validation Message box. Apply the changes to the Properties.

  4. To complete the form add the Button element, then save your form, publish it, and view it in your browser.
  5. To test, click the Submit button without entering anything. You should find that the form does not submit and an error message is displayed.

    Adding Features to your Joomla! Form using ChronoForms

How it works...

The only special thing to notice about this is that the validation we used was validate-one- required and not the more familiar required. Checkbox arrays, radio button groups, and select drop-downs will not work with the required option as they always have a value set, at least from the perspective of the JavaScript that is running the validation.

There's more...

Validating the checkbox server-side

If the checkbox is really important to us, then we may want to confirm that it has been checked using the server-side validation box.

We want to check and, if our box isn't checked, then create the error message. However, there is a little problem—an unchecked checkbox doesn't return anything at all, there is just no entry in the form results array.

Joomla! has some functionality that will help us out though; the JRequest::getVar() function that we use to get the form results allows us to set a default value. If nothing is found in the form results, then the default value will be used instead.

So we can add this code block to the server-side validation box:

<?php
$agree = JRequest::getString('check0[]', 'empty', 'post');
if ( $agree == 'empty' ) {
return 'Please check the box to confirm your agreement';
}
?>

Note: To test this, we need to remove the validate-one-required class from the input in the Form HTML.

Now when we submit the empty form, we see the ChronoForms error message.

Adding Features to your Joomla! Form using ChronoForms

Notice that the input name in the code snippet is check0[]. ChronoForms doesn't give you the option of setting the name of a checkbox element in the Form Wizard | Properties box. It assigns a check0, check1, and so on value for you. (You can edit this in the Form Editor if you like.) And because checkboxes often come in arrays of several linked boxes with the same name, ChronoForms also adds the [] to create an array name. If this isn't done then only the value of the last checked box will be returned.

Locking the Submit button until the box is checked

If we want to make the point about terms and conditions even more strongly then we can add some JavaScript to the form to disable the Submit button until the box is checked.

We need to make one change to the Form HTML to make this task a little easier. ChronoForms does not add ID attributes to the Submit button input; so open the form in the Form Editor, find the line near the end of the Form HTML and alter it to read:

<input value="Submit" name="submit" id='submit'
type="submit" />

Now add the following snippet into the Form JavaScript box:

// stop the code executing
// until the page is loaded in the browser
window.addEvent('load', function() {
// function to enable and disable the submit button
function agree() {
if ( $('check00').checked == true ) {
$('submit').disabled = false;
} else {
$('submit').disabled = true;
}
};
// disable the submit button on load
$('submit').disabled = true;
//execute the function when the checkbox is clicked
$('check00').addEvent('click', agree);
});

Apply or save the form and view it in your browser.

Now as you tick or untick the checkbox, the submit button will be enabled and disabled.

Adding Features to your Joomla! Form using ChronoForms

This is a simple example of adding a custom script to a form to add a useful feature. If you are reasonably competent in JavaScript, you will find that there is quite a lot more that you can do.

There are different styles of laying out both JavaScript and PHP and sometimes fierce debates about where line breaks and spaces should go. We've adopted a style here that is hopefully fairly clear, reasonably compact, and more or less the same for both JavaScript and PHP. If it's not the style you are accustomed to, then we're sorry.

Adding an "other" box to a drop-down

Drop-downs are a valuable way of offering a list of choices to your user to select from. And sometimes it just isn't possible to make the list complete, there's always another option that someone will want to add. So we add an "other" option to the drop-down. But that tells us nothing, so we need to add an input to tell us what "other" means here.

Getting ready

We'll just add one more element to our basic newsletter form. We haven't used a drop-down before but it is very similar to the check-box element from the previous recipe.

How to do it...

  1. Use the Form Wizard to create a form with two TextBox elements, a DropDown element, and a Button element.
  2. The changes to make in the element are:
    • Add "I heard from" in the Label
    • Change the Field Name to "hearabout"
    • Add some options to the Options box—"Google", "Newspaper", "Friend", and "Other"

    Leave the Add Choose Option box checked and leave Choose Option in the Choose Option Text box. Apply the Properties box.

  3. Make any other changes you need to the form elements; then save the form, publish it, and view it in your browser.

    Adding Features to your Joomla! Form using ChronoForms

  4. Notice that as well as the four options we added the Choose Option entry is at the top of the list. That comes from the checkbox and text field that we left with their default values.

    It's important to have a "null" option like this in a drop-down for two reasons. First, so that it is obvious to a user that no choice has been made. Otherwise it's very easy for them to leave the first option showing and this value—Google in this case—will be returned by default. Second, so that we can validate select-one-required if necessary. The "null" option has no value set and so can be detected by validation script.

  5. Now we just need one more text box to collect details if Other is selected.
  6. Open the form in the Wizard Edit; add one more TextBox element after the DropDown element. Give it the Label please add details and the name "other".

    Even though we set the name to "other", ChronoForms will have left the input ID attribute as text_4 or something similar. Open the Form in the Form Editor and change the ID to "other" as well. The same is true of the drop-down. The ID there is select_2, change that to hearabout.

  7. Now we need a script snippet to enable and disable the "other" text box if the Other option is selected in the drop-down. Here's the code to put in the Form JavaScript box:

    window.addEvent('domready', function() {
    $('hearabout').addEvent('change', function() {
    if ($('hearabout').value == 'Other' ) {
    $('other').disabled = false;
    } else {
    $('other').disabled = true;
    }
    });
    $('other').disabled = true;
    });

    This is very similar to the code in the last recipe except that it's been condensed a little more by merging the function directly into the addEvent().

    Adding Features to your Joomla! Form using ChronoForms

  8. When you view the form you will see that the text box for please add details is grayed out and blocked until you select Other in the drop-down.

Make sure that you don't make the please add details input required. It's an easy mistake to make but it stops the form working correctly as you have to select Other in the drop-down to be able to submit it.

How it works

Once again, this is a little JavaScript that is checking for changes in one part of the form in order to alter the display of another part of the form.

There's more...

Hiding the whole input

It looks a little untidy to have the disabled box showing on the form when it is not required. Let's change the script a little to hide and unhide the input instead of disabling and enabling it.

To make this work we need a way of recognizing the input together with its label. We could deal with both separately, but let's make our lives simpler. In the Form Editor, open the Form HTML box and look near the end for the other input block:

<div class="form_item">
<div class="form_element cf_textbox">
<label class="cf_label"
style="width: 150px;">please add details</label>
<input class="cf_inputbox" maxlength="150" size="30"
title="" id="other" name="other" type="text" />
</div>
<div class="cfclear">&nbsp;</div>
</div>

That <div class="form_element cf_textbox"> looks like it is just what we need so let's add an ID attribute to make it visible to the JavaScript:

 

<div class="form_element cf_textbox" id="other_input">

Now we'll modify our script snippet to use this:

window.addEvent('domready', function() {
$('hearabout').addEvent('change', function() {
if ($('hearabout').value == 'Other' ) {
$('other_input').setStyle('display', 'block');
} else {
$('other_input').setStyle('display', 'none');
}
});
// initialise the display
if ($('hearabout').value == 'Other' ) {
$('other_input').setStyle('display', 'block');
} else {
$('other_input').setStyle('display', 'none');
}
});

Apply or save the form and view it in your browser. Now the input is invisible see the following screenshot labeled 1 until you select Other from the drop-down see the following screenshot labeled 2.

Adding Features to your Joomla! Form using ChronoForms

The disadvantage of this approach is that the form can appear to "jump around" as extra fields appear. You can overcome this with a little thought, for example by leaving an empty space.

See also

  • In some of the script here we are using shortcuts from the MooTools JavaScript framework. Version 1.1 of MooTools is installed with Joomla! 1.5 and is usually loaded by ChronoForms. You can find the documentation for MooTools v1.1 at http://docs111.mootools.net/

Version 1.1 is not the latest version of MooTools and many of the more recent MooTools script will not run with the earlier version. Joomla 1.6 is expected to use the latest release.

ChronoForms 3.1 for Joomla! site Cookbook 80 recipes for building attractive and interactive Joomla! forms
Published: August 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

(For more resources on ChronoForms, see here.)

Sending an SMS message on submission

ChronoForms has the built-in ability to send e-mails. Sometimes though you need something more immediate—like a text message sent to a mobile phone. This isn't a built in feature, but it's not hard to add.

Getting ready

You'll need to find a web service that will send SMSes for you. It's possible that your phone provider has a service; but for this example we'll use the API from Clickatell (http://www.clickatell.com) who claim to cover over 800 networks in more than 220 countries.

You'll need to sign up to a service and find the specific details of its API. Clickatell offers ten free credits for testing.

You'll need a simple form to test with; if you don't have one then our standard newsletter form will do perfectly well.

How to do it...

  1. We are going to use the ChronoForms cURL plug-in for this recipe. This is one of the ChronoForms plug-ins that comes with the installation and is accessed from the left hand column of the Forms Manager. The cURL and ReDirect plug-ins are siblings. Both enable us to send form data to other websites. Use the cURL plug-in when only the data needs to be transferred and the ReDirect plug-in when you need to send the user to the other site as well. You usually need to send the user when they have to authorize something, for example to sign in to a payment site like PayPal.
  2. Here, we just need to send data to Clickatell so the cURL plug-in is the one to use.

  3. You can access the plug-in configuration by checking the box beside the form name and clicking the plug-in name in the left hand column. Here is the cURL plug-in configuration dialogue.

    We have no connection with or experience of Clickatell and they are used here as an example, not in any way as a recommendation.
    API (Application Programming Interface) is a set of functions that are made available to allow external users to interact with the service.

    Adding Features to your Joomla! Form using ChronoForms

    Notice that there is a message at the top of the dialogue telling us that the cURL function was found on the server. cURL is an optional part of PHP and though most sites will have it installed, a few may not and will not be able to use this plug-in. (If this happens to you, talk to your ISP who can probably arrange to turn it on.)

    This tab—one of four in the dialog—contains a section at the top with inputs that ChronoForms has created, matching the inputs in our form. (Here "button_2" is the submit button.) Below that is a text area where we can add other data that we want to send.

  4. If you click the cURL params tab and take a quick look, you will see that the top box is "Target URL" which is where we will tell ChronoForms where we want to send the data.

    With that in mind, let's get some information about the Clickatell API.

    Let's assume that we have a client who wants to receive a SMS message saying "Form submitted, check your mail now" when this form is submitted on their website. In this case we need to call the same phone number every time.

    Clickatell have a range of ways that you can connect to their service. We'll use the simplest here—connecting through a URL, their HTTP/S service. We're going to use the test instructions from their site which say:

    • Have the number you wish to send to ready in international format, for example 448311234567
    • Open your browser (for example, Internet Explorer), and type in your info in the address bar in the following sequence:http://api.clickatell.com/http/sendmsg?user=xxxxx&passwo rd=xxxxx&api_id=xxxxx&to=448311234567&text=Meet+me+at+ho me
    • The text of your message must be formatted so that + signs replace spaces between words as shown here

    We need to break that long URL up into its separate parts. The formal structure of a URL is formally defined in a document called RFC3986. Here's an example from that document:

    foo://example.com:8042/over/there?name=ferret#nose
    \_/ \______________/\_________/ \_________/ \__/
    | | | | |
    scheme authority path query fragment

    In the Clickatell URL we have the scheme and path before the ? and the query after it.

  5. In the cURL plug-in dialogue put the scheme and path—http://api.clickatell.com/http/sendmsg in the Target URL box on the cURL params tab and, while you are there set the Flow control to After Email.

    The only reason for doing so in this case is that if the plug- in is set to Before Email it will not run unless Send Emails is set to Yes on the Form General tab.

  6. Then we break the query part up into separate parameter+value pairs by splitting it at the & signs. We get this list:

    user=xxxxx
    password=xxxxx
    api_id=xxxxx
    to=448311234567
    text=Meet+me+at+home

    The user, password, and api_id will take the values you got when you signed up at Clickatell; the value of to is the client's phone number in international format (44 is the UK country code, it would be 1 for North America, and so on); and the value of text is the message.

    All of these values stay the same each time a form is submitted. As they have constant values, we can enter them all into the textarea part of the General tab in the cURL plug-in configuration, remembering to replace the spaces in the message with +.

    Here's an example we can use for a first test; those used previously aren't real values, so the test won't actually send a message though:

    user=greyhead
    password=mysecret
    api_id=987xx123
    to=1234567890
    text=Form+submitted+–+check+your+mail+now

    Remember to keep the message all on one line:

    Adding Features to your Joomla! Form using ChronoForms

  7. Set Debug to On for the plug-in so that we can see the output, save the plug-in configuration, enable the plug-in in the Form Plugins tab if necessary, and then go to the form and submit it.
  8. Here's the result from submitting exactly the data used previously:
  9. Now we haven't got a valid api_id for this test, so the message is not sent. But we do get an error message back from Clickatell (see the last line of the debug listing) so we know that we delivered our data successfully to their API.

How it works...

The cURL functionality is a set of PHP code that is built to allow just this kind of interaction between one computer and another over the internet using some standard protocols, in particular the HTTP POST protocol used by forms.

The ChronoForms cURL plug-in provides a simple way to use a small part of the cURL functionality with our forms and form data. There are many cURL options, most of which aren't accessible through the plug-in (see the PHP documentation at http://php.net/ manual/en/book.curl.php for much more information).

Signing up to a newsletter service

We've been using that newsletter form for a long time now but haven't yet mentioned how we are going to send out the newsletters. One way to do this is to use a hosted newsletter service. There are many of these available each with slightly different offerings. Some familiar names include Aweber, MailChimp, Constant Contact, iContact, and half a dozen or so others.

Adding Features to your Joomla! Form using ChronoForms

Each of these services will have an API that can be accessed to update records. Some of these can be very rich and complex, others almost non-existent. However, all of them have suggestions for a form that you can include on your website for newsletter signups. This form code will give us enough to sign up our user automatically to the service.

We will work with iContact here but the same principals will apply to any of the other services.

Getting ready

We first need to find the "sign-up" form code for our newsletter service provider. iContact has a little wizard that generates a form in two versions—the Manual Sign-up Form is the one we want as it shows all of the form information.

How to do it...

  1. Here's the HTML code the iContact sign-up wizard produces, with some styling and validation code removed:

    <form method=post
    action="https://app.icontact.com/icp/signup.php"
    name="icpsignup" id="icpsignup636" accept-charset="UTF-8" >
    <input type=hidden name=redirect
    value="http://www.icontact.com/www/signup/thanks.html" />
    <input type=hidden name=errorredirect
    value="http://www.icontact.com/www/signup/error.html" />

    <div id="SignUp">
    <table width="260" class="signupframe" border="0"
    cellspacing="0" cellpadding="5">
    <tr>
    <td valign=top align=right>Email</td>
    <td align=left>
    <input type=text name="fields_email">
    </td>
    </tr>
    <tr>
    <td valign=top align=right>Last Name</td>
    <td align=left>
    <input type=text name="fields_lname">
    </td>
    </tr>
    <input type=hidden name="listid" value="9999">
    <input type=hidden name="specialid:9999" value="XAPD ">
    <input type=hidden name=clientid value="123456">
    <input type=hidden name=formid value="777">
    <input type=hidden name=reallistid value="1">
    <input type=hidden name=doubleopt value="0">
    <tr>
    <td> </td>
    <td>
    <input type="submit" name="Submit" value="Submit">
    </td>
    </tr>
    </table>
    </div>
    </form>

    The parts that interests us are—the form Action URL https://app.icontact.com/icp/signup.php, and then the list of input names and values which we can extract from the surrounding HTML:

    The first two match up to the two fields in our form, the remainder have the same values whatever values are entered into the form.

    The redirect and errorredirect inputs will not have any effect working with cURL so we can leave those out.

  2. So we can use the cURL plug-in just as we did in the last recipe, but this time we will link the first two input names here to the corresponding form fields.

    Adding Features to your Joomla! Form using ChronoForms

    Remember to add the Target URL on the second tab, then save the plug-in configuration. Open the form in the Form Editor, enable the plug-in on the Plugins tab and Apply or Save the form.

  3. View the form in your browser and test it.
  4. Note that the IDs shown here are not valid so this exact data will not work. However, with the correct IDs this form successfully adds a new record to the iContact database, except that here iContact is setup to use First Name and Last Name fields and we've put both parts into the Last Name field. It would be simple to add an extra input to our form to handle this.

How it works...

We are pulling out the critical information from the form that the iContact wizard created and using the cURL plug-in to submit that as though it was coming from a form on our site.

See also

  • The previous recipe in this article shows another way of using the cURL plug-in.

Adding a conversion tracking script

If you are running a commercial site then you may want to use one of the conversion tracking services to record the customer action after submission. Here we'll use the Google tracking code as an example; others will be very similar.

Google Conversion Tracking is not the same as Analytics which track every page on your site. Google Analytics (and other similar services) need the code on every page and the best way to do this is either with a custom module (for example, the gh Google Analytics module), or by adding the code to your template.

Getting ready

You can use this with any form but you will need to have the ID codes for your own Google AdWords account to use it.

How to do it...

  1. The conversion tracking code has one slightly different requirement to other form scripts. We only want to show it after conversion so we don't want the code in the Form HTML, but in one of the OnSubmit After boxes instead. The OnSubmit After box is preferred but the OnSubmit Before will work as well, as long as you have Send Emails set to Yes on the Form General tab.
  2. Here's one of the example scripts from the Google AdWords™ Conversion Tracking Setup Guide:

    <!-- Google Code for Purchase Conversion Page -->
    <script language="JavaScript" type="text/javascript">
    <!--
    var google_conversion_id = 1234567890;
    var google_conversion_language = "en_US";
    var google_conversion_format = "1";
    var google_conversion_color = "666666";
    if (5.0) {
    var google_conversion_value = 5.0;
    }
    var google_conversion_label = "Purchase";
    //-->
    </script>

    <script language="JavaScript"
    src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://www.googleadservices.com/pagead/conversion.js">
    </script>

    <noscript>
    <img height=1 width=1 border=0
    src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://www.googleadservices.com/pagead/conversion/1234567890/
    ?value=5.0&label=Purchase&script=0">
    </noscript>

    You'll see that there are three parts to this script:

    • A JavaScript that sets some parameter values
    • A link to download a script from Google
    • A "noscript" script to allow conversion tracking for users without JavaScript enabled

    You could just put this code as it is into the OnSubmit box and it will work fine most of the time.

    If you want to be a little more elegant then you can use a little PHP to load the first two parts from the page head rather than the body. Note that you can't use the ChronoForms JavaScript box as that only works when the form is displayed and that's not what we want here.

    <?php
    $script = "
    var google_conversion_id = 1234567890;
    var google_conversion_language = "en_US";
    var google_conversion_format = "1";
    var google_conversion_color = "666666";
    if (5.0) {
    var google_conversion_value = 5.0;
    }
    ";
    $doc =& JFactory::getDocument();
    $doc->addScriptDeclaration($script);[/code]
    $doc->addScript( "http://www.googleadservices.com/pagead/
    conversion.js" );
    ?>
    <noscript>
    <div style="display:inline;">
    <img height=1 width=1 border=0 src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://www.googleadservices.
    com/pagead/conversion/1234567890/?value=5.0&label=Purchase&scri
    pt=0">
    </div>
    </noscript>

  3. That really is all that is required except to note that you must make sure that the ChronoForms "Thank you" page is displayed in order for the script to be delivered.

Summary

This article taught us some ways to use ChronoForms, such as adding a "terms and conditions" checkbox, linking an "other" box to a select drop-down, sending an SMS message when the form is submitted, signing up to an offsite newsletter service and adding a Google conversion tracking script.


Further resources on this subject:


ChronoForms 3.1 for Joomla! site Cookbook 80 recipes for building attractive and interactive Joomla! forms
Published: August 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Bob Janes

Bob Janes has been involved in IT of one form or another throughout his working career. In the last decade he’s worked mainly on CMS support and development, first with E-Xoops, more recently with Joomla! and WordPress. He’s been the principal support person for ChronoForms for the last three years and has made more than 12,000 posts answering user questions. Bob has an extensive knowledge of Joomla! and WordPress and he enjoys solving the problems involved in building interactive sites on these CMSs.

Books From Packt


Joomla! 1.5: Beginner's Guide
Joomla! 1.5: Beginner's Guide

Joomla! Social Networking with JomSocial
Joomla! Social Networking with JomSocial

Joomla! 1.5 Site Blueprints
Joomla! 1.5 Site Blueprints

Mastering Joomla! 1.5 Extension and Framework Development Second Edition
Mastering Joomla! 1.5 Extension and Framework Development Second Edition

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

Joomla! 1.5 Templates Cookbook
Joomla! 1.5 Templates Cookbook

Joomla! with Flash
Joomla! with Flash

Joomla! 1.5 Multimedia
Joomla! 1.5 Multimedia


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software