📖 PHP Enhanced Form Processing
Single Item Fields
Processing single item data fields from a web form is the easiest processing we will do. When we validate a single line text field, we can usually just check to see if tit is empty. If it's not empty, we just grab the value and store it in a variable for future use. Radio buttons and select lists are pre-populated from an array or a database. To make them sticky, we need to add the "checked" property to the input tag. This takes a little more doing than just storing a value input by the user.
Radio Buttons and Select Lists
When we process radio buttons and select lists, we need to check for validation errors and prepare any submitted information for re-display to the user (sticky forms). Like other fields, we will first check the form submission for a selection and, if we find one, capture it for later use. If we don't find one, we will set an error and trigger a validation error. If we have a long list of items or one that is dynamic (loaded on-demand from a database), we will need a way to process the list. Here we create an array of the items for the list, then use the array to help in processing the form input.
The code for doing all this is rather lengthy. The code shown is for a radio button list but is similar to a select list. Here's the basic process.
- We will process for an empty submission, setting an error on empty but also capturing the value if not.
- When we capture the value of the user selected item, we will also set it's input tag to "checked".
- We will use an array of items for setting up the form and for checking form submission values to set a "checked" value (sticky forms) for an item that was submitted by the user.
- We will display the form initially blank and then with the checked value for re-display on errors. If no errors are found, we will display the output.
Example
<?php
$toy = NULL; // sticky form default value
$toyError = NULL; // supress error messages
$toyList = NULL; // for the radio button form list
$valid = false; // data validation flag
// create an array of toys
$toyArray = array('Doll', 'Bike', 'Board Game', 'Football');
foreach ($toyArray as $toyName){
$toyChecked[$toyName] = NULL;
}
// check to see if the form has been submitted if so process the data.
if (isset($_POST['submit'])) {
$valid = true;
if (empty($_POST['toy'])){ // set error and re-display the form
$toyError = '<span class="text-danger">Required</span>';
$valid = false;
} else { // field not empty
$toy = $_POST['toy']; // grab the value of the selected toy
if (in_array($toy, $toyArray)) { // check to see which toy was selected
$toyChecked[$toy] = 'checked'; // set for sticky form
}
}
}
if ($valid){ // display the form results on the page
// if you wanted to redirect to a new page, you would do that here
$pageContent = <<<HERE
<h2>Welcome!</h2>
<p>Your favorite musical toy is $toy.</p>
HERE;
} else { // build the form for display - include warnings and sticky fields
foreach ($toyArray as $toyName) { // build the radio button list
$toyList .= <<<HERE
<input type="radio" name="toy" id="$toyName" value="$toyName" $toyChecked[$toyName]>
<label for="$toyName">$toyName</label> \n
HERE;
}
$pageContent = <<<HERE
<fieldset>
<legend> Sample Form </legend>
<form method="post" action="radio-button-validation.php">
<div class="form-group">
<label for="toy">Favorite Toy ~ Pick 1 $toyError</label><br>
$toyList
</div>
<div class="form-group">
<button type="submit" name="submit" value="Submit" class="btn btn-primary">Submit</button>
</div>
</form>
</fieldset>
HERE;
}
// assemble the html output
if(isset($_POST['submit'])){
$pageContent .= "<pre>";
$pageContent .= print_r($_POST, TRUE);
$pageContent .= "</pre>";
}
$pageTitle = "Radio Button Validation";
include 'scripts/template.php';
?>
Checkboxes
When processing checkboxes from forms it is beneficial to code them so they create and array when submitted. To do this, you need to add square brackets [ ] to the name attribute for the checkbox field. After that it's very similar to how you would process radio buttons or drop down select lists.
Here's an example of how to code for checkboxes that includes how to handle their data for sticky forms and validating errors. While errors are often just a matter of checking for empty fields, we might also want to check for a specific number of items to be checked. For that, we'll need a conditional statement to check how many items were selected. The example below checks for the field having 2 selections. You can modify this to meet your specific needs.
<?php
$car1 = $car2 = NULL; // variables used in the redirect
$carsError = NULL; // error for incorrect input by user
$carList = NULL; // for checkbox form list
$valid = false; // data validation flag
$carsArray = array('Chevy', 'Ford', 'Toyota', 'Honda', 'BMW', 'Porche');
foreach ($carsArray as $carIndex => $carName){
$carChecked[$carIndex] = NULL;
}
// check to see if the form has been submitted if so write out the data.
if (isset($_POST['submit'])) {
$valid = true;
if (isset($_POST['cars'])){ // check to see if user selected any items
$countCars = COUNT($_POST['cars']); // count number of items user selected
foreach ($_POST['cars'] as $index => $car) { // step through the form data
$selectedCars[] = $car; // create a new array of user selected items
if (in_array($car, $carsArray)) { // check to see if user selceted matches list
$carChecked[$index] = "checked"; // check any items user selected
} // end if
} // end foreach
if ($countCars == 2){ // check to see if selected the appropriate number of items
$car1 = $selectedCars[0]; // set selected items to individual variables (optional)
$car2 = $selectedCars[1]; // set selected items to individual variables (optional)
} else { // set error for inaccurate number of items
$carsError = '<span class="text-danger">Must Select Only 2</span>';
$valid = false;
}
} else { // set error for no selection
$carsError = '<span class="text-danger">Required</span>';
$valid = false;
}
}
if ($valid){
// redirect to new page on valid process
header("Location: new-page.php?car1=$car1&car2=$car2");
exit();
} else { // build the checkbox list
foreach ($carsArray as $carIndex => $carName) {
$carList .= <<<HERE
<input type="checkbox" name="cars[$carIndex]" id="$carIndex" value="$carName" $carChecked[$carIndex]>
<label for="$carIndex">$carName</label> \n
HERE;
}
$pageContent = <<<HERE
<fieldset>
<legend> Sample Form </legend>
<form method="post" action="form-validation.php">
<div class="form-group">
<label for="cars">Favorite Cars ~ Pick 2 $carsError</label><br>
$carList
</div>
<div class="form-group">
<button type="submit" name="submit" value="Submit" class="btn btn-primary">Submit</button>
</div>
</form>
</fieldset>
HERE;
}
// assemble the html output
if(isset($_POST['submit'])){
$pageContent .= "<pre>";
$pageContent .= print_r($_POST, TRUE);
$pageContent .= "</pre>";
}
$pageTitle = "Checkbox Validation";
include 'scripts/template.php';
?>
Other Examples
To see this form at work, visit the professor's Form Validation sample page.