PHP Tutorial

Step 14

PHP Tutorial

In this tutorial we will create a simple twitter copycat. In step 14 we will create field specific error messages.

Step 14

1. Our forms already display a nice behavior when there are errors. They show an error message and don’t lose their data. But if the form is very large, it might be difficult for the user to identify the specific field that caused the error. To handle this problem we will display an error message in front of the field that caused the problem.

Our current error handling code that detects if the username already exists whe a new user is registering is this (actions/users/register.php):

if (strpos($e->getMessage(), 'users_pkey') !== false)
  $_SESSION['error_messages'][] = 'Duplicate username';
else $_SESSION['error_messages'][] = 'Error creating user';

We will start by changing this code so that the error is also stored in an array that has specific field errors:

if (strpos($e->getMessage(), 'users_pkey') !== false) {
  $_SESSION['error_messages'][] = 'Duplicate username';
  $_SESSION['field_errors']['username'] = 'Username already exists';
}
else $_SESSION['error_messages'][] = 'Error creating user';

2. In our config/init.php file, we will send this new array to Smarty and delete it. Just has we do with the other ephemeral session variables.

$smarty->assign('FIELD_ERRORS', $_SESSION['field_errors']);

unset($_SESSION['field_errors']);

3. Now we just have to show this message in our templates/users/register.tpl template:

<form action="{$BASE_URL}actions/users/register.php" method="post">
  <label>Name:<br>
    <input type="text" name="realname" value="{$FORM_VALUES.realname}">
  </label>
  <br>
  <label>Username:<br>
    <input type="text" name="username" value="{$FORM_VALUES.username}">
    <span class="field_error">{$FIELD_ERRORS.username}</span>
  </label>
  <br>
  <label>Password:<br>
    <input type="password" name="password" value="">
  </label>
  <br>
  <input type="submit" value="Register">
</form>

4. We will also add some CSS:

.field_error {
  color: red;
  font-size: 70%;
}

In step 15 we will allow users to upload images into their profiles.