Note: SproutCMS comes with a
Forms module, which allows operators to create forms via a GUI, with no programming. These forms save submissions into a database and optionally send the data to a configurable email address. The Forms module is quite powerful, and in many cases, it provides all the functionality that's required without having to write custom code. For more on this see the SproutCMS user manual.
If you are a developer and need to write custom code, read on...
The recommended way to deal with forms is to add two methods to a controller - one to view the form, and one to handle its submissions. The method which displays the form should use the Form and Fb classes to:
- Load any existing data which the user has entered from the session.
- Display the appropriate form fields, prefilled with the appropriate data from the session or, if appropriate, some default values.
The method which handles the form submission should use the Validator and Validity classes to:
- Validate the POST data
- If there's an erroneous input, redirect the user back to the form, with the data they submitted retained in the form fields
- If the input passes validation, do whatever processing is expected (e.g. save the data into the database), then redirect the user to a thanks page or similar.
Redirects are used on the form submission handler because if a user tries to refresh a page which has had POST data submitted, they receive a rather confusing message asking them whether or not to resubmit the data. This is to be avoided at all costs.