Urdu English
English English Deutsch Deutsch Español Español Français Français Italiano Italiano Nederlands Nederlands Português Português Русский Русский Ελληνικά Ελληνικά

Welcome to Jumi! >> Tutorial >> Self calling forms in a Joomla! content

There is a lot of people who wish to publish their custom forms in a Joomla! content.

To meet their needs I decided to write this tutorial. The tutorial is dedicated to Joomla! 1.0.x coding beginners but intermediate ones may found some tricks useful as well.

In this step by step tutorial you will learn

  • what self colling forms are and for what purpose they serve,
  • some most useful php and Joomla! 1.0.x tricks that are relevant to self calling forms. E.g.:
    • how a script catches that a user has sent data,
    • how to recognize an URL address at which the script runs,
    • how to switch off the specific Joomla! page cache off,
    • what Joomla! specific object $database, $my are, where to find their methods and their description,
    • etc.

What self calling forms are and for what purpose they serve

Every form collects some data from responders.

Collected data do not remain in a form but they are - usually after pressing submit button - sent somewhere. They are sent to some processing script that "sits" on another URL address and that - after possible preprocessing - writes data into the database or/and sends them to an e-mail address.

This is the most common approach. And on that approach rely standard Joomla! forms components.

But it is possible to live without forms component, it is possible to have our own forms to be included into an content article. Forms can send collected data to self and process them. They are so called self calling forms.

It is even possible even more: to show the form results in the same content article.

In this tutorial I will show you how.

Because there has to be some php script there that manipulates with form data I will make use of Jumi plugin for including this scripts into the content. Should you prefer any other plugin for php script inclusion into Joomla! content you can use it as well.

Demo form description

Although the following demo form is very concrete you can write every form you can imagine by the approach explained in this tutorial.

Do not make tests on your public production server but on your local host only!

Let us assume we want

  • a voting form that collects answers on 3 mutually exclusive questions,
  • to save answers into a database together with date and time of the answer and together with an user's identification,
  • to show "thank you" announcement and summary of the results but only to those users who voted.

Basic strategy

Splitting the code into several pieces, functional and logical blocks offers many advantages. Although I will not discussed the advantages here I will follow this general good practice here.

There are two main logical blocks in our task:

  • show form + collect data + verify them + save data to a database (self calling form)
  • read data from a database and show the results.

So I will split our application into two script files too: self_call_form.php and show_results.php.

We will go into the details in the following.

But let us start with a database first.


Let our database table name is xxx_mytable_test where xxx stands for your Joomla! database prefix. Some Joomla! users have jos prefix others have mos prefix. I will assume jos prefix in the following.

I repeat our task is to store record date and time, user identification and an answer.

Without going into MySQL database and table design details that can be found elsewhere the structure of the table described in MySQL language will be:

CREATE TABLE IF NOT EXISTS `jos_mytable_test` (
`id` int(11) NOT NULL auto_increment,
`recordtime` datetime NOT NULL default '0000-00-00 00:00:00',
`user_id` varchar(15) NOT NULL default 'host',
`answer` int(6) NOT NULL default '0',

The field id was added just for table record unique identification.

You have to create the table in your Joomla database. Verify, that your prefix is jos_. If it is still mos_, change the table prefix.

You can create table via phpMyAdmin either manually or automatically by copy-paste of the MySQL statement above.

I will assume the table jos_mytable_test is created from now.


There are basically two methods by which a form communicate with its environment: POST and GET. GET sends (and reads) data from URL appendix. We will not use GET method here.

Method POST writes data to global php variable $_POST. So we have full access to the data sent here.

General algorithm of the self_call_form.php

If there are no relevant data in $_POST, i.e. there is no answer from an user, then show form. If the user answered, then thank him and write the answer (and other data) into the database.

The algorithm above translated into php language looks like this code:

function self_form()
 //Radio button name (here "answer") must be a column name in a database too!!!

 $anchor = "myform"; //the $anchor variable we will need later
 echo "<a name = $anchor></a>"; //the html anchor we will need later
 echo "<blockquote>"; //form container

 if(!isSet($_POST['answer'])) //if there is no answer then write the form
  $return_url = get_return_url($anchor);
  echo "<form name='my_form' action=$return_url method='post'>";
  echo "<h3>Have you found this tutorial helpful?</h3>";
  echo "<input type='radio'  name='answer' value='1'> Absolutely no.\n";
  echo "<input type='radio'  name='answer' value='2'> So so.\n";
  echo "<input type='radio'  name='answer' value='3'> Yes. Thanks for it.\n";
  echo "<input type='submit' onClick='return checkForm(this.form)'
   value='Submit' class='button'/>";
  echo "</form>";

 else //if there is an answer thank and write the answer into the database
  echo "<b>Thank you for your voting</b>";

 echo "</blockquote>";

The explanation and some tricks

PHP function isSet('answer') checks weather 'answer' exists in $_POST.

We want the form to send data to self. That means to the same URL address (form and its processing script can be found at the same URL). We can use hard coded URL address of a page or, as in our case, we can get the URL from Joomla environment using a simple trick. Using the trick is better then the first hard coded approach because our code is reusable in various pages without any touch.

So here comes the trick contained in the function get_return_url($anchor).

Function get_return_url()
function get_return_url($anchor)
 if ($query_string = mosGetParam( $_SERVER, 'QUERY_STRING', '' ))

  $return = 'index.php?' . $query_string;

  $return = 'index.php';
 // an url starts with index.php now
 // converting & to &amp; for xtml compliance

 $return = str_replace( '&', '&amp;', $return );
 //adding anchor to the end of url

 $return .="#$anchor"; //adding anchor to url
 //prepand http:// to the beginning of the url
 return sefRelToAbs($return);


There is no miracle in it. The function just returns URL address where it runs (in our form). Including the anchor.

Why I have included the (html) anchor into the return address?

Imagine that our form is at the bottom of a very long page. If it were not for the anchor then after sending data user will see the top of the page and has to scroll down. With anchoring user will be return to the place he voted.

I will like to turn your attention to Joomla! specific function mosGetParam() too. It is the most useful function. And should be used in you forms intensively.

The general description of mosGetParam()can be found here. One of the practical usage follows:

Instead of using:


it is better to use:

mosGetParam($_POST, 'somename')

because it not only does some trimming of unwanted user input but there are some other useful options in it.

However if you have many data to be processed it can be rather time consumptive to withdraw all values from $_POST one by one: either by direct accessing them or via mosGetParam() function. There is an another trick: use php function extract($_POST) that builds variables and assigns them names from all the content of $_POST.

Notice we use $_SERVER in the function get_return_url(). $_SERVER is another php global variable like $_POST and can be of some usage in your scripts too. If you do not know the content of variables you can show them in your scripts using var_dump($somoevaribale) function.

Function checkForm()

This is the validation javascript function that validates user input against some rules. That email is really an email address, that name is not empty, etc.

Again: you can find various validation scripts on hundreds Internet sources.

In our demo form we will validate that user has selected an "answer" radio button. If there is no "answer" do not submit data but show an alert:

<SCRIPT type="text/javascript">
function checkForm(theForm) {
 var why = "";
  for (i=0; i<theForm.answer.length; i++) {

   if (theForm.answer[i].checked) {
    var checkvalue = theForm.answer[i].value;

  why += checkRadio(checkvalue);
  if (why != "") {
   why += "\nIf you think it is our mistake, let us known please.";
   return false;

  return true;
function checkRadio(checkvalue) {
 var error = "";
  if (!(checkvalue)) {

   error = "You have not selected any option.\n";
   return error;

There are no tricks and no miracles here so let us go to the writing data to the database.

Function write_data()

You can spare much time if you use Joomla! objects and methods instead of using standard MySQL database function. I mean using database->load..., database->query, etc. Very descriptive manual can be found here.

function write_data($value)
//if user is logged save his id otherwise save 'host'

 global $database, $my;
 if ($my->id)
  $user_id = $my->id;

  $user_id = "host";
 $database->setQuery( "INSERT INTO #__mytable_test
   (id, recordtime, user_id, answer)
    VALUES  ('' , '". date('Y-m-d H:i:s')."', '".$user_id."' , '".$value."');" );
 $database->query(); //write data


Nothing interesting here except global Joomla! variable $my. It contains user id, name, his e-mail etc. Again: try to use var_dump($my) in your code and you will see the structure and the content.

Validating query:

I have not included any validation that data was actually written. You can do it if you want. Just substitute the line $database->query(); by
if (!$database->query()) { //write data and if error occurs alert

  echo "<script> alert('".$database->getErrorMsg()."'); </script>";

So we have all building blocks of our self calling form now.

You can try it immediately (provided you have jos or mos_mytable_test table created).

But there is one more thing...

Not for all of us the application behavior will be as generally expected: after submitting the form will be still visible and there will be no "thank you" announcement.

This will occur for those whose Joomla! cache is on.

And here comes another trick: switching off the whole Joomla cache is easy but switching off the cache for one of the Joomla pages seems to be THE problem.

The big problem with very simple solution.

The cache hack was described in Joomla! forum:

Edit /includes/Cache/Lite.php
You'll see "function save($data..."

function save($data, $id = NULL, $group = 'default')

 if ($this->_caching) {


function save($data, $id = NULL, $group = 'default')

 if(strpos($data,'<!--nocache-->') !== false) {
  $this->_caching = 0;

 if ($this->_caching ) {

then, create a module with


in the body, and publish it to any displayed position (Users won't see it)... Then just enable that module on any page you don't want cached...

I am just adding that "nocache directive" can be included into the content as well.

Summary of self_call_form.php

So there is the whole content of self_call_form.php:

defined( '_VALID_MOS' ) or die( 'Restricted access' ); //security reasons

<SCRIPT type="text/javascript">
function checkForm(theForm) {
function checkRadio(checkvalue) {

function self_form()

function get_return_url($anchor){
function write_data($value){

//executive code starts here
//executive code ends here

N.B.: the whole script is "wrapped" into the executive self_form() functions. No script variables are defined outside any functions so there is no risk the variables will interact with other 3rd party or Joomla! variables in an unpredictable way.


That's all for the self calling form: show form + collect data + verify them + save data to a database.

Now write into your article

{jumi [somepathway/self_call_form.php]}

and test it.

First you will see

jumi form input

and after your voting (only after voting) you can see the result of the second part (show_results.php):

jumi form output

The second part - presenting the results obtained from the database - is much easier then the previous part.


defined( '_VALID_MOS' ) or die( 'Restricted access' );

function show_results()
 global $database;
 echo "<!--nocache-->"; //not necessary but useful here

 $radios_name = "answer"; // must be a column in a database too!!!
 if(isSet($_POST[$radios_name])) {//show results for those who voted only
  echo "<blockquote>";
  echo "<h3>This tutorial was</h3>";
  $database->setQuery( "SELECT $radios_name, COUNT(id) AS numitems
   FROM #__myform_test GROUP BY $radios_name");
  $rows = $database->loadObjectList();
  foreach ( $rows as $row ){ // walking through answers

   switch ($row->answer){
    case 1:
     echo "not useful for ".$row->numitems." readers,\n";
    case 2:
     echo "so so useful for ".$row->numitems." readers and\n";
    case 3:
     echo "very useful for ".$row->numitems." readers\n";

 echo "</blockquote>";

Now write into your content just under previous jumi plugin declaration:

{jumi [somepathway/show_results.php]}

and test it.

I do not think there is much for explanation except manipulating database and rows objects. Again: go to Joomla! API description.


Everything was solved, everything was written. You can download the whole script here.