Creating HTML Forms in Sahana

The Sahana source code comes with a library that is useful for creating HTML form elements. However, the library is not extensively documented. This document tries to provide a bit of guidance on how to use the library functions.


Setting Up

The example described here can be downloaded. We will create a simple Hello World module. Thus, we will create a directory named hw in Sahana's mod directory. The hw directory will contain the following files:           -- Required main file for the module. Contains shn_hw_default() method.           -- Required conf file. Adds the hw module to the main menu.      -- Creates the HTML form  -- Process the HTML form POST query.         -- A library containing local (Trinity) form-processing functions

The file contains the following statements, which add the hw module to the main menu. The module's menu item is named Hello World

$conf['mod_hw_name'] = _("Hello World");
$conf['mod_hw_menuorder'] = 2;

The file contains two key methods, shn_hw_mainmenu(), and shn_hw_default(). The first method is used to construct the module's main menu. In this case we are adding a single menu item titled Say Hello. This is the menu item that will bring up the form by invoking the say_hello() method. The menu entry associates the menu item with that method:

function shn_hw_mainmenu()
    global $global;
    $module = $global['module'];
    shn_mod_menuopen(_lc("Hello World"));                    // Create the module menue
    shn_mod_menuitem("say_hello","Say Hello");
    include $global['approot']."/inc/";  // Include the main menu

The other method is the default method that is called when the hello world module is selected of Sahana's main method. It simply displays a message in HTML code:

function shn_hw_default()
<div id="home">
    <?=_("<h2>Welcome to the Hello World Module<BR>Choose an item from the Hello World menu.</h2>")?>
<br />

Libraries To Include

Since you will be using library functions for this task, you need to include the correct libraries. Here are the libraries that are used in this example. These include statements should be placed at the beginning of your main file.

global $global;
include_once $global['approot']."/inc/";       // Include the forms library
include_once $global['approot']."/inc/";       // Needed for the HW menu.
include_once $global['approot']."/inc/";   // Needed to validate menu items.
include_once ("");            // Local Library: Contains the _shn_form_select_gender() function
include_once ("");         // Contains the code for the form.
include_once ("");     // Contains the method to process the form.

Coding the Form

For our example, all of the code that creates the HTML form is contained in the shn_hw_say_hello() method in the file:

function shn_hw_say_hello() {

<center><h2><?=_("Hello Form  - Give me your name and I'll say hello")?> </h2>
<h2>&lt?;=_("When you are finished, click \"Submit\".")?> </h2></center><BR>
<div id="formcontainer">
    shn_form_fopen("process_hello");                                   // Open the Form
    shn_form_fsopen('Get the Name');                                   // The group of fields get's the user's name
    $extra_opts['req']=true;                                           // The name is a required field
    shn_form_text(_("Your name  : "),'name','size="50"',$extra_opts);  // Create a text field element
    shn_form_date(_("Date of Birth : "),'dob', $initdate=NULL);        // Create a date element
    echo "<br>";
    _shn_form_select_gender($error,NULL);                              // Create a gender drop-down menu (Trinity library)
    echo "<br>";
    shn_form_fsclose();                                                // Close this group of elements
?> <br /> <center>
    shn_form_submit("Submit");                       // Create the submit button
?> </center> <br />
    shn_form_fclose();                               // Close the form
?> </div>
} // say_hello()

As you can see, the form is created by a mixture of PHP and HTML code. Creating HTML elements, such as text fields, date fields, is done by calling functions such as shn_form_date() that are available in the Sahana library or the Trinity library. These are described below.

One important point is that the call to the shn_form_open() function, must pass it the name of the function that will process the form data. In this case, the name of the function that handles the data is process_hello.

Another important point is that you must remember the symbolic names that you give the various form elements. For example, the textfield in this example is given the name name because it inputs the user's name. This symbolic name will be used to retrieve the form data.

Processing Form Data

Sahana form data is processed as a POST query. This means that the data is stored by the server in a variable named $_POST. This variable is an associative array whose elements are indexed by the names of the various HTML elements. For example, if the textfield in your form is named name, you would retrieve the value from that textfield with the expression $_POST['name'].

Here's the process_hello() function (from the process_hello() file:

function shn_hw_process_hello() {

    global $global;
//    include_once $global['approot']."/mod/vr/";   // Local Library: Contains dbgpost()
//    dbgpost($_POST);                                                   // Uncomment to display post values

    $name = $_POST['name'];
    if (!shn_validate_field($name, 'Name', $max_len=30, $check_null=true)){  // If name is null
    $gender = $_POST['opt_gender'];
    $gender_str = "male";
    if ($gender != "mal") {
        $gender_str = "female";

    $dob_entered = $_POST['dobY'] . $_POST['dobM'] . $_POST['dobD'];
    if (!shn_valid_date($dob_entered, $check_null=false, $pattern='/^\d{4}\d{2}\d{2}$/')){ // If date is invalid
    } else if (shn_is_null($dob_entered)) {        // If date is null
        $dob_formatted = "unknown";
    } else {
       $dob_formatted = $_POST['dobM']  . "-" . $_POST['dobD'] . "-" . $_POST['dobY'];  // Format the date

    if ($error) {
        $hellostring = "Sorry. Please try again.";
    } else {
        $hellostring = "Hello " . $name . ". <BR>You are a  " . $gender_str . " and your birthday is " . $dob_formatted;
<div id="hello">
    <?=_("<center><h2> $hellostring </h2></center>")?>
<br />
} // process_hello()

As you can see, in the case of the date field, Sahana contains library functions that can be used to validate form input data. For example, in this example, we are validating that the name field is not null and that the date is properly formatted.

Forms Function Library

The Sahana library for building forms is the, which is stored in the inc directory. Here is a list of the functions and a brief description.

Function SignatureDescription
shn_form_extra_opts($extra_opts) Adds additional attributes to an HTML element
shn_form_fopen($act, $mod = null, $form_opts = array('req_message'=>true)) Open the HTML form
shn_form_fclose() Close the HTML form
shn_form_submit($name, $submit_opts = null) Generate the submit button
shn_form_fsopen($label = null) Open a fieldset, which is a group of fields
shn_form_fsclose() Close a fieldset
shn_form_button($name, $button_opts = null, $extra_opts = null) Create an HTML button element
shn_form_text($label, $name, $text_opts = null, $extra_opts = null ) Create an HTML text field
shn_form_hidden($hidden_vars) Create an HTML hidden element
shn_form_checkbox($label, $name, $text_opts = null, $extra_opts = null) Create an HTML checkbox
shn_form_select($options,$label, $name,$select_opts = "", $extra_opts = null) Create an HTML drop-down menu
shn_form_radio($options,$label, $name,$select_opts = "", $extra_opts = null) Create an HTML radio button
shn_form_opt_select($opt_field, $label, $select_opts = "", $extra_opts = null) Create a select field based on field options
shn_form_opt_multi_select($opt_field, $label, $select_opts = "", $extra_opts = null) Create a select field based on field option
shn_form_multi_select($name,$options, $label, $select_opts = "", $extra_opts = null) Create a multi-select field
shn_form_opt_checkbox($opt_field,$extra_opts=null) Create checkboxes based on a field option
shn_form_textarea($label, $name, $text_opts = null, $extra_opts = null) Create an HTML text area
shn_form_upload($label, $name, $extra_opts = null) Create an HTML upload element
shn_form_label($label, $caption, $extra_opts = null) Create an HTML label (a pseudo element)
shn_form_password($label, $name, $text_opts = null, $extra_opts = null) Create a password element
shn_form_date($label, $name = 'date', $initdate = null ) Create a date element
shn_form_date($label, $name = 'date') Create a fancy date element with a popup calendar
shn_form_fopen_alt($act, $mod = null, $form_opts = array('req_message'=>true)) An alternative open tag??

Form Validation Functions

Validate a field
function shn_valid_len_range($field, $minlength, $maxlength)Validate the field length range
function shn_valid_zipcode($country, $zipcode)Validate the zipcode
function shn_valid_phone($field)Validate the phone number format
function shn_valid_email($field,$required=false)Validate email address format
function shn_valid_date($date,$check_null=false,$pattern='/^\d{4}-\d{2}-\d{2}$/')Validate the date
function shn_valid_number($str,$pattern='/^\d+$/')Validate a number (is a number)
function shn_is_null($field)Validate whether a field is null
function shn_is_opt_field($opt_field,$opt_value)
function shn_is_location($field)Validate a location
function shn_clean($field)Clean a string
function shn_validate_field($field,$desc,$max_len,$check_null=false)
function shn_validate_opt_field($type,$field,$desc,$max_len,$array=false)
function shn_validate_user_name($field)Validate the user name
function shn_validate_password($field)Validate a password

Additional Form Functions

We have created some additional form elements that are contained in the vr module in the file These functions all require access to the Sahana database in order to initialize drop-down menus.

To use these functions you must include the vr/ file.

_shn_form_select_gender($error=false,$value=NULL,$label=NULL)Select a gender (male/female) from a drop down
_shn_form_select_idtype($error=false,$value=NULL,$label=NULL)Select an id-type (license, passport, etc) from a drop down
_shn_form_date($label, $name = 'date', $initdate = null, $required=false, $format='YYYY-MM-DD') Another date element
_shn_form_select_task($error=false,$value_selected=NULL, $label=NULL, $select_opts=NULL, $extra_opts=NULL) Select a task from a drop down
_shn_form_select_volunteer_skills($person_id, $post_id,$error=false,$value_selected=NULL, $label=NULL, $select_opts=NULL, $extra_opts=NULL) Select volunteer skills from a menu
_shn_form_select_organization($error=false, $value_selected=NULL, $label=NULL, $select_opts=NULL, $extra_opts=NULL) Select an organization from a list
_shn_form_select_project($error=false, $value_selected=NULL, $label=NULL, $select_opts=NULL, $extra_opts=NULL) Select a project from a list
_shn_form_select_specialities($error=false,$value=NULL) Select a specialty from a list
_shn_location_form_volunteer($from,$to,$value=NULL)Select a location from a list
_shn_form_get_contact_info($error=false,$org=true,$po_uuid=null)Display contact information from the DB