Re-filling form fields using the API
This tutorial is for version 2.x of the API, which is for Form Tools 3. If you're using Form Tools 2, please check out this tutorial instead.
Once you get into the wonderful world of creating multi-page forms (or even single-page forms with server-side validation) you often need to access and display the values the user has entered up to that point. Here's a couple of cases where this is handy:
- If a user clicks back to a previous page to re-edit a field
- If you want to include a "review" page where the user can see the values they're entered, to ensure they're submitting the correct information.
- Your form contains a CAPTCHA that prevents them from continuing until it's entered correctly. If entered incorrectly, you'll need to re-enter the form fields to prevent them having to type them in again.
The good news is that if you're using the API functions, this isn't terribly hard to do. The bad news is that it *does* require getting your hands a little dirty. This tutorial is less about the API than it is about basic PHP.
The initFormPage() method
If you've dutifully followed the instructions in the API and the multi-page tutorial, you've added the
initFormPage()
PHP call to each of your pages. In addition to the other stuff it does, this method
also returns all form values in a single PHP array.
The following explains how to re-fill fields of all different types. Several of the examples assume that PHP short tags are enabled on your system. If not, you can use the full PHP tags.
The @
symbol isn't strictly necessary; it's included in case you have error reporting turned up
high. If the array keys don't exist, it will throw a minor notice. The @
character suppresses
those notifications.
Form field types
Text fields
To re-fill a text field, you just need to load the value attribute from the $fields array, like so:
The second line is similar to the first except that it encodes the content. This is necesary if the field is likely to contain double quotes. If it DOES, the HTML will be invalidated and it won't display properly. In most other cases, you don't need to encode it.
Textareas
HTML-encoding the content for textareas is not necessary, since the content is not loaded within a double-quote encapsulated attribute.
Radio Buttons
Checkboxes
Note the [] characters on group of checkboxes section. To pass along multiple values for a group of form fields with the same name, those characters are necessary.
Dropdown
Multi-select Dropdown
Note the [] characters in the name attribute of the select tag. They are required to pass along multiple values for a single form field like this.