Using ChronoForms to add More Features to your Joomla! Form

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 the previous article we covered:

  • 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

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

  • Showing a YouTube video
  • Adding a bar-code to a for m e-mail
  • Adding a character counter to a textarea
  • Creating a "double drop-down"

(For more resources on ChronoForms, see here.)

Showing a YouTube video

This is the "not really a form" recipe in this article, it just opens a little door to some of the other, more unexpected, capabilities of ChronoForms.

For the most part Joomla! protects the content you can display on your pages; it's easy to show HTML + CSS formatted content, more difficult to show PHP and JavaScript. There are many modules, plug-ins and extensions that can help with this but if you have ChronoForms installed then it may be able to help.

ChronoForms is designed to show pages that use HTML, CSS, PHP, and JavaScript working together. Most often the pages created are forms but nothing actually requires that any form inputs are included so we can add any code that we like.

ChronoForms will wrap our code inside <form>. . .</form> tags which means that we can't embed a form (why would we want to?), but otherwise most things are possible.

 

Getting ready

You will need the ID of the YouTube video that you want to display. We're going to use a video from a conference at Ashridge Business School, but any video will work in essentially the same way.

This recipe was developed for this particular video to force display of the HD version. At that time HD was a new option on YouTube and was not readily accessible as it is now.

How to do it...

  1. Find the video you want on YouTube and look for the links boxes in the right hand column. Here we've clicked on the "customize" icon—the little gear wheel—to open up the options menu.

  2. When you've set the options you want copy the code from the Embed box. Here is the code from this video with some added line breaks for clarity:

    <object width="425" height="344">
    <param name="movie"
    value="http://www.youtube.com/v/2Ok1SFnMS4E&hl=en_GB&fs=1&">
    </param>
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <embed src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://www.youtube.com/v/2Ok1SFnMS4E&hl=en_GB&fs=1&"
    type="application/x-shockwave-flash" allowscriptaccess="always"
    allowfullscreen="true" width="425" height="344">
    </embed>
    </object>

  3. To create a good looking page, we are going to add some HTML before and after this snippet:

    <h3>Video Postcards from the Edge</h3>
    <div>The video of the 2008 AMOC Conference</div>
    <div style='margin:6px; padding:0px; border:6px solid silver;
    width:425px;'>
    <object width="425" height="344">
    <param name="movie" value="http://www.youtube.com/v/2Ok1SFnMS4E&hl
    =en&fs=1&ap=%2526fmt%3D18"></param>
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <embed src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://www.youtube.com/v/2Ok1SFnMS4E&hl=en&fs
    =1&ap=%2526fmt%3D18" type="application/x-shockwave-flash"
    allowscriptaccess="always" allowfullscreen="true" width="425"
    height="344"></embed></object>
    </div>
    <div>Some more text . . .</div>

    If you look closely, you'll see that there is also a new parameter in the URL—&ap=%2526fmt%3D18—which is there to force the HD version of the video to be used.

  4. Paste this code into the Form HTML box of a new form, save, and publish it.

    Of course, it would be entirely possible to embed the video and to add form inputs in the same page, maybe to ask for comments or reviews.

How it works...

Very simply ChronoForms allows you to embed scripts into the page HTML that are not permitted in standard Joomla! articles.

Adding a barcode to a form e-mail

Sometimes it's important to add a unique identifier to the form response, for example travel or event tickets. In this recipe we will look at generating a "random" identifier and adding it to the form e-mail as a scannable barcode.

Getting ready

We're going to need a simple form. Our newsletter form will be perfect although we'll be adding to the code in the Form HTML box.

We'll need a simple function to create the "random identifier" which we will see shortly.

Lastly we"ll need code to generate a barcode. Rather than taking time reinventing this particular wheel, we're going to use a PHP program created by Charles J Scheffold and made available for use or download from http://www.sid6581.net/cs/php-scripts/barcode/.

How to do it...

  1. First, grab a copy of the barcode.php file from sid6581.net.
  2. We'll need to make this file accessible to our form. So let's create a new folder inside the ChronoForms front-end folder.

    You'll probably need to use an FTP client to do this, or install the "exTplorer" Joomla! extension which will allow you to create folders from within the Joomla! Site Admin interface.

    • Browse to [root]/components/com_chronocontact and create a new includes folder
    • Copy the standard Joomla! index.html file from the com_chronocontact folder into the new folder
    • Upload the barcode.php file into the new includes folder
  3. Now, we are going to add the function to create a "random" identifier to the Form HTML. This is a small function that creates an alphanumeric string when it is called.

    <?php
    if ( !$mainframe->isSite() ) { return; }
    /*
    function to generate a random alpha-numeric code
    using a specified pattern
    *
    * @param $pattern string
    * @return string
    */
    function generateIdent($pattern='AA9999A')
    {
    $alpha = array("A","B","C","D","E","F","G","H",
    "J","K","L","M","N","P","Q","R","S","T","U","V","W",
    "X","Y","Z");
    $digit = array("1","2","3","4","5","6","7","8","9");
    $return = "";
    $pattern_array = str_split($pattern, 1);
    foreach ( $pattern_array as $v ) {
    if ( is_numeric($v) ) {
    $return .= $digit[array_rand($digit)];
    } elseif ( in_array(strtoupper($v), $alpha) ) {
    $return .= $alpha[array_rand($alpha)];
    } else {
    $return .= " ";
    }
    }
    return $return;
    }
    ?>

    We call this function using generateIdent() or generateIdent('pattern') where the pattern is a string of As and 9s that defines the shape of the ident we want. The default is AA9999A, giving idents like KX4629G. This will be perfectly fine for our example here.

    We also want to add the ident into the form and we'll use a hidden field to do that, but to make it visible we'll also display the value.

    <?php
    $ident = generateIdent();
    echo "<div>Ident is $ident</div>";
    ?>

    <input type='hidden' name='ident' id='ident'
    value='<?php echo $ident; ?>' />

    In day to day use we probably wouldn't generate the ident until after the form is submitted. There is often no useful value in displaying it on the form and essentially the same code will work in the OnSubmit boxes. However, here it makes the process clearer to generate it in the form HTML.

  4. We can add both these code snippets to our form just before the submit button element. Then apply or save the form and view it in your browser.

    The layout may not be very elegant but the Ident is there. Refresh the browser a few times to be sure that it is different each time.

    It's simpler and tempting to use serial numbers to identify records. If you are saving data in a table then these are generated for you as record IDs. It does create some problems though; in particular, it can make it very easy to guess what other IDs are valid and if, as we often do, we include the ID in a URL it may well be possible to guess what other URLs will be valid. Using a random string like this makes that kind of security breach more difficult and less likely.

  5. We said though that we'd generate a barcode, so let's develop this form one more step and show the barcode in the form.

    If you look at the code in barcode.php, it shows a list of parameters and says what we can use. For example:

    <img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="barcode.php?barcode=123456&width=320&height=200">

  6. We need to modify this a little to link to the new folder for the file and to add our generated ident value:

    <img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="/components/com_chronocontact/includes/barcode.
    php?barcode=<? php echo $ident;?>&width=320&height=8">

    This code can go in place of the "echo" line we used to display the ident value:

    <?php
    $ident = generateIdent();
    echo "<img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original='".JURI::base()
    ."components/com_chronocontact/includes/barcode.php?barcode="
    .$ident."&width=320&height=80' />";
    ?>

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

    There we have it—a bar code in our form showing the random ident that we have created.

    If you don't see any graphic and the code appears to be correct then you may not have the PHP GD graphics library installed. Check on the AntiSpam tab for any of your forms and you will see a GD Info box. The GD library is now included in the vast majority of PHP installations. If you don't have it then check with your ISP to see if the library can be enabled.

  8. Now that's actually not of much use except to show that it works, you can't scan a bar code off the screen. Where we want it is in our Email template.

    The code to add to the template is:

    <div>Your code: {ident}</div>
    <img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="<?php echo JURI::base().'components/com_chronocontact/
    includes/'; ?>barcode.php?barcode={ident}&width=280&height=100"
    />

  9. As this includes some PHP, we can't add it using the Rich Text Editor. First we need to go to the Email Setup | Properties box and set Use Template Editor to No, apply the Properties, then apply the form and go to the Email Template tab.

    To avoid an "oddity" in the current release of ChronoForms it may be necessary to comment out the generateIdent() function code block in the Form HTML, while you create an Email Setup. Just put /* & */ before and after the block if you get a blank page or see a PHP Error message about re-declaring the function.

  10. Now click on the Email Template tab and paste the code at the end of the textarea.
  11. Submit the form to test.

    We now have a printable e-mail complete with a barcode showing our random ident.

How it works...

In this recipe we did a couple of things. We added some more complex PHP to the Form HTML that we had before and we imported a PHP script found on the internet and successfully used that in combination with ChronoForms.

There are many hundreds of useful scripts available for almost any conceivable function. Not all are of good quality and not all will work in this way but, with a little work, a surprising number will function perfectly well.

There's more...

We said earlier that it might be better to generate the ident after the form is submitted. Here's the code to use in the OnSubmit Before code box to get the same result in the e-mail:

<?php
if ( ! $mainframe->isSite() ) { return; }
JRequest::setVar('ident', generateIdent());

/*
function to generate a random alpha-numeric code
using a specified pattern
*
* @param $pattern string
* @return string
*/
function generateIdent($pattern='AA9999A')
{
$alpha = array("A","B","C","D","E","F","G","H",
"J","K","L","M","N","P","Q","R","S","T","U","V","W",
"X","Y","Z");
$digit = array("1","2","3","4","5","6","7","8","9");
$return = "";
$pattern_array = str_split($pattern, 1);
foreach ( $pattern_array as $v ) {
if ( is_numeric($v) ) {
$return .= $digit[array_rand($digit)];
} elseif ( in_array(strtoupper($v), $alpha) ) {
$return .= $alpha[array_rand($alpha)];
} else {
$return .= " ";
}
}
return $return;
}
?>

If you use this, then you can remove all of the additional code from the Form HTML box leaving just the basic HTML generated by the Form Wizard. The Email template code remains as we created it previously.

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:

Read more about this book

(For more resources on ChronoForms, see here.)

Adding a character counter to a textarea

Some users can get just a bit long-winded when presented with a text area to type into. When that happens it would be useful to be able to show the number of characters remaining and to block the input of extra characters if the limit is exceeded.

Getting ready

We'll use a very simple form created by the Form Wizard with just two elements—a TextArea and a Button. We will need to know the ID of the text area; by default it will be text_0, the same as the element name.

How to do it...

  1. Create the form, save it, and view it in your browser.

  2. Notice that although we've labeled the textarea 50 chars max it takes nearly 100 without complaint. In fact you could keep on typing for a long time and the textarea would just scroll down and accept the input.
  3. We're going to add some JavaScript to the Form JavaScript box to count the characters:

    window.addEvent('load', function() {
    // execute the check after each keystroke
    $('text_0').addEvent('keyup', function() {
    // set the maximum number of characters
    max_chars = 50;
    // get the current value of the input field
    current_value = $('text_0').value;
    // get current character count
    current_length = current_value.length;
    // calculate remaining chars
    remaining_chars = max_chars current_length;
    // show the remaining characters
    $('counter').innerHTML = remaining_chars;
    });
    });

  4. We would want to show the results of our calculation on the form somewhere, so we'll add some extra text to the textarea label:

    <label class="cf_label" style="width: 150px;">50 chars max
    <br /><span id='counter'>50</span> chars left</label>

    That span, with id='counter' is where we'll show the characters remaining.

    This works very nicely to count the remaining characters. Unfortunately, it does nothing to stop more characters being entered, all that happens is that we quickly show a negative number of characters remaining.

  5. We need some actions to block more characters being entered. We could disable the input as we did for the Submit button in an earlier recipe, but this stops the user editing their entry. What we will do is to trim the entry to 50 characters and show a warning.

    We need to add some more script in place of the innerHTML line previously shown:

    // Change color if remaining chars are five or less
    if ( remaining_chars <= 5 ) {
    $('text_0').setStyle('background-color', '#F88');
    $('text_0').value
    = $('text_0').value.substring(0, max_chars-1);
    if ( remaining_chars <= 0 ) {
    remaining_chars = 0;
    }
    } else {
    $('text_0').setStyle('background-color', 'white');
    }
    $('counter').innerHTML = remaining_chars;
    });

    This script does nothing much if there are more than five characters left except to clear any warnings. If there are less than five characters left, it changes the text area background to a reddish color; if there are no characters left it will trim the text to 50 characters preventing anything new being added.

  6. This is a fairly simple variant of this kind of script, more elaborate versions can show "thermometer" indicators of the characters left in place of the simple count here. And we could have more subtle messages too!

How it works...

The JavaScript runs a little function to count the characters each time a key click is recorded in the textarea. When the count gets near 50, it shows a warning and then acts when the count reaches 50.

This, like the last recipe, is an example of taking a script published on the Internet for free use and modifying it to work with a ChronoForms Form.

Creating a double drop-down

A 'double drop-down' is a pair of linked drop downs where the options in the second dropdown depend on the selection in the first drop-down.

As an example, we will consider a cookbook which has a series of chapters, each of which contain several recipes. We might have a list of chapters in the first drop-down and then show the recipes from the selected chapter in the second drop-down.

For simplicity here we'll just use two chapters each with three recipes:

  • Chapter 1: Recipe a, recipe b, and recipe c
  • Chapter 2: Recipe x, recipe y, and recipe z

There are two fundamentally different ways of approaching this recipe. The first is to load all of the options into the Form HTML before the page is sent to the browser and to hide the unwanted options; the second is to load none of the options but to use an AJAX request to get the options we need when we need them.

Both approaches are useful in different situations. Where there are relatively few options, the "load all" approach is easier and that is what we will use here.

Getting ready

We will need the code for a form with two DropDowns. You can create this with the Form Wizard though we will then edit the code in the Form HTML box.

How to do it...

  1. Here's the Form HTML we will start with:

    <div class="form_item">
    <div class="form_element cf_dropdown">
    <label class="cf_label"
    style="width: 150px;">Chapter</label>
    <select class="cf_inputbox" id="chapter" size="1"
    title="" name="chapter">
    <option value="">Choose Option</option>
    <option value="1">Chapter 1</option>
    <option value="2">Chapter 2</option>
    </select>
    </div>
    <div class="cfclear">&nbsp;</div>
    </div>

    <div class="form_item">
    <div class="form_element cf_dropdown">
    <label class="cf_label"
    style="width: 150px;">Recipe</label>
    <select class="cf_inputbox" id="recipe" size="1"
    title="" name="recipe">
    <option value="">Choose Option</option>
    <option value="a">Recipe a</option>
    <option value="b">Recipe b</option>
    <option value="c">Recipe c</option>
    <option value="x">Recipe x</option>
    <option value="y">Recipe y</option>
    <option value="z">Recipe z</option>
    </select>
    </div>
    <div class="cfclear">&nbsp;</div>
    </div>

    <div class="form_item">
    <div class="form_element cf_button">
    <input value="Submit" name="submit"
    id="submit" type="submit" />
    </div>
    <div class="cfclear">&nbsp;</div>
    </div>

    The Wizard code has been edited to add more meaningful names and IDs to the input elements and to change the option values to simple numbers or letters. Both of these changes make it easier to work with the code using JavaScript.

    As you can see, at the moment all of the recipes are being displayed.

  2. We will now edit the Form HTML to add option groups to the recipe options list:

    <optgroup label="Chapter 1" id="ch_1"
    disabled="disabled" >
    <option value="a">Recipe a</option>
    <option value="b">Recipe b</option>
    <option value="c">Recipe c</option>
    </optgroup>
    <optgroup label="Chapter 2" id="ch_2"
    disabled="disabled" >
    <option value="x">Recipe x</option>
    <option value="y">Recipe y</option>
    <option value="z">Recipe z</option>
    </optgroup>

    Now we have our recipes grouped by chapter and they are all disabled as no chapter is selected.

    You cannot disable individual options in a drop-down list but, as we see, you can disable option groups which makes them very useful for this kind of form.

  3. Next we need to add a little script to check the chapters and enable the corresponding recipe option group:

    window.addEvent('load', function() {
    // set the chapter count
    var num_chapters = 2
    // code to execute when the chapter changes
    $('chapter').addEvent('blur', function() {
    var chapter = $('chapter').value;
    var optgroup = 0;
    // loop through the chapters
    for ( var i = 1; i <= num_chapters; i++ ) {
    if ( i == chapter ) {
    // if this chapter is selected
    $('ch_'+i).disabled = false;
    } else {
    // if this chapter is not selected
    $('ch_'+i).disabled = true;
    }
    }
    });
    });

    Most of this script is self evident except perhaps for 'ch_'+i – this is adding the current chapter number to ch_ to give us ch_1, ch_2, and so on, which are the IDs of the recipe option groups.

  4. Add this script snippet to the Form JavaScript box, apply or save the form, and reload it in your browser window.

    Now the corresponding option group is enabled when we choose a chapter and if we reselect Choose Option'in the Chapter box, then all of the recipe options are disabled again.

  5. We can take this one step further by hiding the disabled option groups with a few more lines in the script:

    window.addEvent('load', function() {
    var num_chapters = 2
    // hide all the recipes to start with
    for ( var i = 1; i <= num_chapters; i++ ) {
    $('ch_'+i).setStyle('display', 'none');
    }
    $('chapter').addEvent('blur', function() {
    var chapter = $('chapter').value;
    var optgroup = 0;
    for ( var i = 1; i <= num_chapters; i++ ) {
    if ( i == chapter ) {
    $('ch_'+i).disabled = false;
    $('ch_'+i).setStyle('display', 'block');
    } else {
    $('ch_'+i).disabled = true;
    $('ch_'+i).setStyle('display', 'none');
    }
    }
    });
    });

    Here we are using .setStyle('display', 'none') and .setStyle('display', 'block') to hide and unhide the option groups.

  6. Now we have a working double-drop down. Because we have kept all of the options in place the standard ChronoForms "validate-selection" will work as usual.

    There are other ways of doing this by hiding and unhiding whole drop-downs, or by rewriting all of the options in a dropdown using a script. These can be made to work but are all more complex than this approach using option groups.

There's more...

At the beginning we mentioned the "load none" AJAX approach. This is more useful if there are many options, or the choice of options is more complex, for example if values are read from a database table depending on values in the form.

Summary

This article taught us some ways to use ChronoForms, such as showing a YouTube video, adding a barcode to an e-mail, adding a character counter to a textarea input, and creating a "double drop-down" where the second changes depending on the first.


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


No votes yet
IrretenoG by
Awesome Post. I add this Blog to my bookmarks.
sakdreasy by
I just sent this post to a bunch of my friends as I agree with most of what you’re saying here and the way you’ve presented it is awesome.
I’ve been visiting your blog by
I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for sharing.
You certainly deserve a round by
You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material
Hi:) Test, just a test u4 by
Greetings... your blog is very interesting and beautifully written.
Good Info VPS by
I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for sharing.
Great Post by
You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material
Good Post by
I just book marked your blog on Digg and StumbleUpon.I enjoy reading your commentaries.
Good Info by
Awesome Post. I add this Blog to my bookmarks.

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
6
k
j
M
7
i
Enter the code without spaces and pay attention to upper/lower case.
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