HTML and CSS Reference
In-Depth Information
need to add new toys to the list, I can just add them to the array definition and they'll
automatically be included on the page. I show you how the code that displays the field
works shortly.
Presenting the Form
Aside from validating form submissions, one of the other important functions of server-
side processing is to prepopulate forms with data when they are presented. Many web
applications are referred to as CRUD applications , where CRUD stands for
create/update/delete. It describes the fact that the applications are used to mostly manage
records in some kind of database. If a user submits a form with invalid data, when you
present the form for the user to correct, you want to include all the data that the user
entered so that he doesn't have to type it all in again. By the same token, if you're writ-
ing an application that enables users to update their user profile for a website, you will
want to include the information in their current profile in the update form. This section
explains how to accomplish these sorts of tasks.
However, before I present the form to the user, I provide a list of errors that the user
needs to correct before the form submission is considered valid. Here's the code to
accomplish that task:
<?php if (!empty($errors)) { ?>
<?php foreach (array_values($errors) as $error) { ?>
<li><?= $error ?></li>
<?php } ?>
<?php } ?>
I use the empty() function yet again to determine whether there are any errors. If there
aren't any, I can go ahead and present the form. If there are any errors, I present them in
a list. First, I create an unordered list; then I use a foreach loop to iterate over the errors.
The $errors variable is an associative array, and the error messages to present are the
values in the array. I use the built-in array_values() function to extract an array con-
taining only the values in the $errors array, and iterate over that array using the foreach
loop. There's something interesting going on here. The body of the foreach loop is
HTML, not PHP code. Look closely and you'll see the opening and closing braces for
the foreach loop. Instead of sticking with PHP for the body of the loop, though, I go
back to HTML mode by closing the PHP script, and I use regular HTML to define the
list items. Inside the list item I use a short tag to present the current error message.
Search WWH ::

Custom Search