Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
20.9.2014 - We have just updated our course layouts and descriptions and added our 2015 schedule.

PHP Form Processing Template

Posted by Garrie (Garrie), 19 September 2002
I was wondering if there is a PHP template for the processing of a form.

What I am thinking about is the normal cycle of a form:

  1. User fills in details on form.
  2. User submits form.
  3. The form is validated.
  4. Details are displayed on another page for user to check.
  5. If not correct, the user is taken back to the
      form, with all of their details filled in.

So does any know if such a template exists?
Since it is such a regular function, I would have thought that it does.

- Garrie

Posted by admin (Graham Ellis), 20 September 2002
Hi, Garrie - welcome, and thanks for posting.

Your question is an excellent one - I've often wondered whether there's an easier way to write applications like you describe than coding from scratch each time.   The answer to many "how to " questions in PHP is "There's a function to do that", but as far as I know that doesn't apply in this case even the the requirement is probably one of the most  common things people do in PHP.

It's struck me as curious that there's an apparent hole like this in  the function provision of PHP, but I've been thinking on further since I saw you post pop up.

First thought - is this something that a function could really do? Probably not, as you hint in your question, you're really thinking of an application template.  So perhaps I should look elsewhere for a solutions (e.g. PEAR) rather than in the PHP base functions. Having said that, session handling also appears to be an application template type requirement, but has been implemented usefully through a series of functions.

Second thought - do applications and validations vary just too much  for it to be practical for function(s) to be provided?  As soon I  sat down and stated thinking "what would the function(s) be called  and do?" and "What would their parameters be", I started coming up with longer specs than I liked, and a number of desisions had to me made whether to go route (a), route (b) or provide an option / flag / extra function that gives users the choice, and also a need  to understand the background and why the choice is being made. Taking the easy way out and just providing - say (a) - could mean  that the function would rule out use of the function set by a significant minority of potential users, even if you went with the most popular choice.   Keep doing that many times over, and you  end up with functions which, good though they are, apply only to a small minority of potential users and leave the others frustrated that they are so close, but don't do the job.

You probably expected a shorter answer.   Ah - my own training is in the area of compiler writing / language specification, etc; it lets me get inside language that I teach (which is superbly useful) but  sometimes sets me off on interesting thoughts.

Actually, I do think there is potential for sets of fucntions written along the lines you suggest.   If you know perl and CGI.pm, look at what Lincoln Stein has done; it's not the same thing, but there's somewhat of a parallel there.   But see what a huge library Lincoln has come up with, and how you have do a ceratin amount of "learning in" to make reasonable use of it.

Garrie - as well as your requirement, I have advise at least one other of our members here about similar needs (and that person has been off coding, I'm sure), and I've been at exactly the same point myself with one of my own apps in the last couple of weeks.   It keeps coming up.    

If it can be done, it should be done and if the do-er can get it easy and general enough, and get some visibility (horrid words like marketing)  for the results, it could take off.

Next step?  Look around widely to see if it's already been done and is out there; I know that your posting is 1 step towards that.  Listen to comments from othere here and elsewhere before re-inventing the wheel.   And then, if it turns out that you can't find what you're looking for, consider writing it to meet your requirement but as general as possible, and documented, so that the rest of us can make good use of it.   Truth be known - could be an exciting project - you might find that you can get some assistance and a small group of like-minded folks (please include me in) could really do something useful


Posted by admin (Graham Ellis), 25 September 2002
I had yet *another* requirement today for something like Garrie's talking about - so did a few experiments.  Wrote my form as follows:

Code:
<form method=POST>
<table border=1>
<tr><td>User name</td><td><?php form_text("uname",$_POST["uname"],$unprob) ;?></td></tr>
<tr><td>Password</td><td><?php form_password("ucode",$_POST["ucode"],$upprob) ;?></td></tr>
<tr><td>Then press</td><td><?php form_submit("","Log in") ;?></td></tr>
</table>
</form>


then functions

Code:
<?php

# This is file form.inc, test version 0.9
# Make up standard form elements

# form_text("uname",$_GET["uname"])
# form_password("ucode",$_GET["ucode"])
# form_submit("","Log in")

function form_text($fieldname,$value="",$alert="",$size="") {
       f_textfamily("text",$fieldname,$value,$alert,$size);
       }
function form_password($fieldname,$value="",$alert="",$size="") {
       f_textfamily("password",$fieldname,$value,$alert,$size);
       }
function form_submit($fieldname,$value="") {
       f_textfamily("submit",$fieldname,$value,"","");
       }
function form_hidden($fieldname,$value="") {
       f_textfamily("hidden",$fieldname,$value,"","");
       }

function f_textfamily($type,$fieldname,$value,$alert,$size) {
       $generate = "<input type=$type";
       if ($fieldname != "") $generate .= " name=$fieldname";
       if ($size > 0) $generate .= " size=$size";
       if ($value != "") $generate .= " value=\"".
               htmlspecialchars($value)."\"";
       $generate .= ">";
       if ($alert != "") $generate .= "&nbsp;".
               "<font color=red>".
               htmlspecialchars($alert).
               "</font>";
       echo ($generate);
       }



And this (with a load of other stuff ...)  gave us the sticky fields and easier tracking from one page to the next, with repeated pages and error reporting if users don't fillin the form right.   Is this a starter towards what folks are looking for?

Posted by Garrie (Garrie), 7 October 2002
Graham,
Well here is my attempt at a template.
I'll have to post it in two parts as it's too big to post in one go.
This is FORM.PHP which uses the functions I've defined.
The next post will contain the details of 'HTML Objects.php'.
- Garrie
Code:
<?php

require('HTML Objects.php');

if (isset($_POST['submit']))
{

  switch ($_POST['submit'])
  {
     case 'Submit':
 
     if (validate())
        {
        displayConfirm();
        exit();
        }
     break;

     case 'OK':
        processForm();
        exit();
     break;

  }

}

?>

<form action="form.php" method="post" name="formName" id="formName">

  <table border="1">
     <tr>
        <td>Text Box</td>
        <td align="center">
           <?php htmlText('textBox','abc','size="10" maxlength="10"'); ?>
        </td>
     </tr>
     <tr>
        <td >Check Box</td>
        <td align="center">
           <table border="0">
              <tr>
                 <td >Apples</td>
                 <td>
                    <?php htmlCheckbox('dessert[]','Apple'); ?>
                 </td>
              </tr>
              <tr>
                 <td>Bananas</td>
                 <td>
                    <?php htmlCheckbox('dessert[]','Banana'); ?>
                 </td>
              </tr>
              <tr>
                 <td>Carrots</td>
                 <td>
                    <?php htmlCheckbox('dessert[]','Carrot'); ?>
                 </td>
              </tr>
              <tr>
                 <td>Doughnuts</td>
                 <td>
                    <?php htmlCheckbox('dessert[]','Doughnut'); ?>
                 </td>
              </tr>
           </table>
        </td>
     </tr>
     <tr>
        <td>Radio Buttons</td>
        <td>
           <table border="0">
              <tr><td><?php htmlRadio('decide','yes'); ?>Yes</td></tr>
              <tr><td><?php htmlRadio('decide','no'); ?>No</td></tr>
              <tr><td><?php htmlRadio('decide','maybe'); ?>Maybe</td></tr>
           </table>
        </td>
     </tr>
      <tr>
          <td>Best Friend</td>
          <td>
<?php
  $options=array("David","John","Fred","Mark","Frankie","Jules");
  htmlSelect("bestFriend[]",$options,'multiple="multiple" size="3"');
?>
         </td>
     </tr>
<tr>
          <td>Favourite Colour</td>
          <td>
<?php
  $options=array('-' => '-','Red'=>'Red', 'Orange'=>'Orange', 'Green'=>'Green', 'Blue'=>'Blue', 'Indigio'=>'Indigo', 'Violet'=>'Violet');
  htmlSelect('colour',$options);
?>
         </td>
     </tr>

     <tr>
         <td>Do you agree with this?</td>
         <td>
             <?php htmlCheckbox('agree','yes'); ?>
         </td>
     </tr>
     <tr><td colspan="2" align="center">
     <input type="submit" name="submit" value="Submit" />
     </td></tr>
  </table>
</form>



Posted by Garrie (Garrie), 7 October 2002
And here is the contents of 'HTML Objects.php'

- Garrie

Code:
<?php


// Assign an error message to a field
function setAlert($fieldName,$msg)
{
  $fieldName=removeBraces($fieldName);
  $GLOBALS['alertMsg'][$fieldName]=$msg;
}

// Retrieve the error message for a field
function getAlert($fieldName){
  $fieldName=removeBraces($fieldName);
  if (isset($GLOBALS['alertMsg'][$fieldName])){
     $msg=' <font color="red">'.$GLOBALS['alertMsg'][$fieldName].'</font><br />';
     unset($GLOBALS['alertMsg'][$fieldName]);
     return ($msg);
  }
}

/* If the fieldname ends with "[]", remove them.
  This is required as when a fieldname with "[]"
  is used as a key, the "[]" are not used.
*/
function removeBraces($fieldName)
{
  if (strpos($fieldName,'[]')!== false)
     {$fieldName=substr($fieldName, 0, -2);}
  return ($fieldName);
}


/* Check if there is a value for the field in $_POST.
  If so then, depending upon the type of field,
  either return the value in $_POST or, "checked" or "selected"
*/
function checkValue($fieldName, $fieldType, $currentValue='')
{
  $key=removeBraces($fieldName);

  if (isset($_POST[$key]))
  {
     $val=$_POST[$key];

     switch ($fieldType)
     {
        case 'checkbox':
        case 'radio':
           if (is_array($val))
           {
               if (in_array($currentValue, $val))
               {$value=' checked="checked"'; }
               else {$value='';}
           }

           else if ($currentValue == $val)
                {$value=' checked="checked"'; }
                else {$value = '';}
        break;

        case 'select':
           if (is_array($val))
           {
               if (in_array($currentValue, $val))
               {$value=' selected="selected"'; }
               else {$value='';}
           }

           else if ($currentValue == $val)
                {$value=' selected="selected"'; }
                else {$value = '';}
        break;

        default:
           $value=$val;
     }
     return ($value);  
  }
}


/* Generate a checkbox field */
function htmlCheckbox ($fieldName, $value='', $attrib='')
{
  $checked = checkValue($fieldName,'checkbox',$value);
  $attrib .= $checked;
  $htmlObject = htmlInput($fieldName, 'checkbox', $value, $attrib);
  echo ($htmlObject);
}

/* Generate a radio button */
function htmlRadio ($fieldName, $value='', $attrib='')
{
  $checked = checkValue($fieldName, 'radio', $value);
  $attrib .= $checked;
  $htmlObject = htmlInput($fieldName, 'radio', $value, $attrib);
  echo ($htmlObject);
}

/* Generate a text box */
function htmlText ($fieldName, $value='', $attrib='')
{
  $value = checkValue($fieldName,'text',$value);
  $htmlObject = htmlInput($fieldName, 'text', $value, $attrib);
  echo ($htmlObject);
}

/* Generate a hidden field */
function htmlHidden($fieldName,$value)
{
  $htmlObject = htmlInput($fieldName,'hidden',$value);
  echo ($htmlObject);
}

/* Generate a select field
  Note that $options should be an array containing
  the options to be displayed.
  If a multiple select field is required, it can be specified
  by including 'multiple="multiple"' in $attrib.
*/
function htmlSelect($fieldName, $options, $attrib='')
{
  $htmlObject  = getAlert($fieldName);
  $htmlObject .='<select '.htmlTag($fieldName,'',$attrib)." >\n";
  reset ($options);
  while (list ($key, $val) = each ($options)) {
     $selected=checkValue($fieldName, 'select', $key);
     $htmlObject .= "   <option value=\"$key\" $selected>$val</option>\n";}
  $htmlObject .="</select>\n";
  echo ($htmlObject);
}

/* Common formatting of the attributes of an INPUT tag */
function htmlInput ($fieldName, $fieldType, $value='', $attrib='')
{  
  $htmlObject  = getAlert($fieldName)."\n";
  $htmlObject .= "<input type=\"$fieldType\" ";
  $htmlObject .= htmlTag($fieldName, $value, $attrib)." />\n";
  return ($htmlObject);
}

/* Common formatting of all HTML tags */
function htmlTag ($fieldName, $value='', $attrib='')
{
  $htmlObject = "name=\"$fieldName\" id=\"$fieldName\" ";

  if ($value != '')
     {$htmlObject .= " value=\"$value\" ";}

  if ($attrib != '')
     {$htmlObject .=" $attrib ";}

  return ($htmlObject);
}


// This function displays the details submitted.
// This is only done very simply here for demonstration and testing.
// However, it is important to note that the details are displayed
// within a form. This combined with the HIDDEN fields makes it
// possible to re-populate the data entry form if the "Change" button is clicked.
function displayConfirm()
{
  echo "<html><head><title>Confirm Details</title><head><body>\n";
  echo "<form action=\"form.php\" method=\"post\" name=\"formName\" id=\"formName\">\n";
  createHidden('$_POST',$_POST);
  echo displayDetails($_POST);
  echo "<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"OK\" />\n";
  echo "<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Change\" />\n";
  echo "</form></body></html>\n";

}


// This function displays in a table the details submitted
// through the form.
function displayDetails($array)
{
  echo "<table border=\"1\">\n";
  reset ($array);
  while (list ($key, $val) = each ($array))
  {
     echo "<tr>\n   <td>$key</td>\n   <td>";
     if (is_array($val)) {displayDetails($val);}
     else {echo $val;}
     echo "   </td>\n</tr>\n";
  }
  echo "</table>\n";
}

/* This creates HIDDEN fields on the confirmation screen
  using the same fieldname and values held in $_POST.
*/
function createHidden($arrayName,$array)
{  
  reset ($array);
  while (list ($key, $val) = each ($array))
  {
     if (is_array($val)) {createHidden($key, $val);}
     else if ($arrayName == '$_POST')
          {htmlHidden($key,$val);}
          else {htmlHidden($arrayName.'[]',$val);}
  }
}



// This function validates the values entered on the form.
function validate()
{

    $ok=true;

     if (!isset($_POST['textBox']) || $_POST['textBox']==''){
        setAlert('textBox','A value is required!');
        $ok=false;
     }

     if (!isset($_POST['decide'])){
        setAlert('decide','Please make a selection');
        $ok=false;
     }

     if (!isset($_POST['bestFriend'])){
        setAlert('bestFriend','You MUST have one friend!');
        $ok=false;
     }

     if (!isset($_POST['colour']) || $_POST['colour']=='-'){
        setAlert('colour','Please pick a colour');
        $ok=false;
     }


     if (!isset($_POST['dessert'])){
        setAlert('dessert','Please select at least one option');
        $ok=false;
     }

     if (!isset($_POST['agree'])){
        setAlert('agree','Please tick this before submission');
        $ok=false;
     }

 return ($ok);

}

/*
 This function should carry out any processing
 of the details submitted, once they have been
 confirmed by the user.
*/
function processForm()
{
  echo 'Your details have been received!';
  return;
}
?>



Posted by Garrie (Garrie), 7 October 2002
I've copied this here to keep all the suggestions together. I have removed part of the quote not related to templating.

- Garrie

on 10/07/02 at 14:45:03, jfp wrote:
...
No talk on templating here though, but I suggest you look at http://smarty.php.net/ for starters, there is another called fast template but smarty is faster and more extendable.

Have the appropriate amound of fun.

jfp



Posted by John_Moylan (jfp), 7 October 2002
Thanks for moving this over to here Garrie, it was naughty of me not to do it myself.

For those of you not privvy to the previous thread (where my smarty template comment came from) it started as a quick chat about XML, which moved onto the separation of content, logic & presentation.

I suggested Garrie look at smarty.php.net, and do so here to!

To give a quick description, smarty is a templating solution for php, it's very very fast (note the use of two very's ) The templates get compiled so are held in memory.

It appears the php community at large is moving over to this too and is actively being developed, unlike some existing templating solutions that have been static for some time.

Anyway, take a look, you won't be dissapointed.

jfp



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

Comment: "Great topic! ..."
Visitor Ranking 4.0 (5=excellent, 1=poor)

Comment by viky (published 2011-02-18) Suggested link.
Great topic! [#3875]

You can Add a comment or ranking or edit your own comments

Average page ranking - 4.0

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho