Forms are the traditional way for most web applications to gather significant information from the user. Whether it's a search form, a login screen or a multi-page registration wizard, Tapestry uses standard HTML forms, with HTTP POST actions by default. In addition, AJAX-based form submission is supported using Zones.
Div | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||
|
Tapestry provides support for creating and rendering forms, populating their fields, and validating user input. For simple cases, input validation is declarative, meaning you simply tell Tapestry what validations to apply to a given field, and it takes care of it on the server and (optionally) on the client as well. In addition, you can provide event handler methods in your page or component classes to handle more complex validation scenarios.
Finally, Tapestry not only makes it easy to present errors messages to the user, but it can also automatically highlight form fields when validation fails.
Contents
Table of Contents |
---|
The Form Component
The core of Tapestry's form support is the Form component. The Form component encloses (wraps around) all the other field components such as TextField, TextArea, Checkbox, etc.
...
The Form component emits a number of component events. You'll want to provide event handler methods for some of these.
...
Next, all the fields inside the form are activated to pull values out of the incoming request, validate them and (if valid) store the changes.
Wiki Markup |
---|
{float:right|width=25%|background=#eee} _For Tapestry 4 Users:_ Tapestry 5 does not use the fragile "form rewind" approach from Tapestry 4. Instead, a hidden field generated during the render stores the information needed to process the form submission. {float} |
After the fields have done their processing, the Form emits a "validate" event. This is your chance to perform any cross-form validation that can't be described declaratively.
...
Handling Events
Main Article: Component Events Forms and Validation
You handle events by providing methods in your page or component class, either following the onEventFromComponent() naming convention or using the OnEvent annotation. For example:
Code Block | ||||
---|---|---|---|---|
| ||||
void onValidateFromPassword() { ...} |
or the equivalent using @OnEvent:
Code Block | ||||
---|---|---|---|---|
| ||||
@OnEvent(value=EventConstants.VALIDATE, component="password") void verifyThePassword() { ...} |
Tracking Validation Errors
...
Storing Data Between Requests
Wiki Markup |
---|
{float:right|width=40%} {info:title=New in Tapestry 5.4} Starting in Tapestry 5.4, the default behavior for server-side validation failures is to re-render the page within the same request (rather than emitting a redirect). This removes the need to use a session-persistent field to store the validation tracker when validation failures occur. {info} {float} |
...
For example, a Login page class, which collects a user name and a password, might look like:
Code Block | ||||
---|---|---|---|---|
| ||||
package com.example.newapp.pages; import com.example.newapp.services.UserAuthenticator; import org.apache.tapestry5.annotations.*; import org.apache.tapestry5.corelib.components.Form; import org.apache.tapestry5.corelib.components.PasswordField; import org.apache.tapestry5.ioc.annotations.Inject; public class Login { @Persist @Property private String userName; |
...
@Property private String password; @Inject private UserAuthenticator authenticator; @InjectComponent("password") private PasswordField passwordField; @Component private Form loginForm; /** * Do the cross-field validation */ void |
...
onValidateFromLoginForm() { if (!authenticator.isValid(userName, password)) { // record an error, and thereby prevent Tapestry from emitting a "success" event loginForm.recordError(passwordField, "Invalid user name or password."); |
...
} } /** * Validation passed, so we'll go to the "PostLogin" page */ Object onSuccess() { return PostLogin.class; } } |
Wiki Markup |
---|
{float:right|width=40%} {info} Note that the onValidateFromLoginForm() and onSuccess() methods are not public; event handler methods can have any visibility, even private. Package private (that is, no modifier) is the typical use, as it allows the component to be tested, from a test case class in the same package. {info} {float} |
Tip |
---|
To avoid data loss, fields whose values are stored in the HttpSession (such as userName, above) must be serializable, particularly if you want to be able to cluster your application or preserve sessions across server restarts. |
The Form only emits a "success" event if the there are no prior validation errors. This means it is not necessary to write if (form.getHasErrors()) return;
as the first line of the method.
...
The Login page template below contains a minimal amount of Tapestry instrumentation and references some of the Bootstrap CSS classes (Bootstrap is automatically integrated into each page by default, starting with Tapestry 5.4).
Code Block | ||||
---|---|---|---|---|
| ||||
<html t:type="layout" title="newapp com.example" xmlns:t="http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <div class="row" |
...
> <div class="span4 offset3"> <t:form t:id="loginForm"> <h2>Please sign in</h2> <t:textfield t:id="userName" t:mixins="formgroup |
...
"/> <t:passwordfield t:id="password" value="password" t:mixins="formgroup"/> <t:submit class="btn btn-large btn-primary" value="Sign in"/> </t:form> </div> </div> </html> |
Rendering the page gives a reasonably pleasing first pass:
The Tapestry Form component is responsible for creating the necessary URL for the form submission (this is Tapestry's responsibility, not yours).
For the TextField, we provide a component id, userName. We could specify the value
parameter, but the default is to match the TextField's id against a property of the container, the Login page, if such a property exists.
As a rule of thumb, you should always give your fields a specific id (this id will be used to generate the name
and id
attributes of the rendered tag). Being allowed to omit the value parameter helps to keep the template from getting too cluttered.
The FormGroup mixin decorates the field with some additional markup, including a <label> element; this leverages more of Bootstrap.
Code Block | ||||
---|---|---|---|---|
| ||||
<div class="form-group"> <label for="userName" class="control-label">User Name</label> <input id="userName" class="form-control" name="userName" type="text"> </div> |
Form Validation
The above example is a very basic form which allows the fields to be empty. However, with a little more effort we can add client-side validation to prevent the user from submitting the form with either field empty.
Validation in Tapestry involves associating one or more validators with a form element component, such as TextField or PasswordField. This is done using the validate parameter:
Code Block | ||
---|---|---|
| ||
<t:textfield t:id="userName" validate="required" t:mixins="formgroup"/> <t:passwordfield t:id="password" value="password" validate="required" t:mixins="formgroup"/> |
Available Validators
Tapestry provides the following built-in validators:
...
Let's update the two fields of the Login page:
Code Block | ||
---|---|---|
| ||
@Persist @Property @Validate("required") private String userName; @Property @Validate("required") private String password; |
Now, we'll rebuild the app, refresh the browser, and just hit enter:
The form has updated, in place, to present the errors. You will not be able to submit the form until some value is provided for each field.
...
It is also possible to perform extra validation there.
...
Code Block | ||
---|---|---|
| ||
/** * Do the cross-field validation */ void onValidateFromLoginForm() { if (!authenticator.isValid(userName, password)) { // record an error, and thereby prevent Tapestry from emitting a "success |
...
" event loginForm.recordError(passwordField, "Invalid user name or password."); } } |
This is the validate event handler from the loginForm component. It is invoked once all the components have had a chance to read values out of the request, do their own validations, and update the properties they are bound to.
...
Entering any two values into the form and submitting will cause a round trip; the form will re-render to present the error to the user:
Notice that the cursor is placed directly into the password field.
Note |
---|
In versions of Tapestry prior to 5.4, a form with validation errors would result in a redirect response to the client; often, temporary server-side data (such as the userName field) would be lost. Starting in 5.4, submitting a form with validation errors results in the new page being rendered in the same request as the form submission. |
Customizing Validation Messages
...
The message can be customized by adding an entry to the page's message catalog (or the containing component's message catalog). As with any localized property, this can also go into the application's message catalog.
...
If there is no message for that key, a second check is made, for fieldId-validatorName-message. If that does not match a message, then the built-in default validation message is used.
For example, if the form ID is "loginForm", the field ID is "userName", and the validator is "required" then Tapestry will first look for a "loginForm-userName-required-message" key in the message catalog, and then for a "userName-required-message" key.
The validation message in the message catalog may contain printf-style format strings (such as %s) to indicate where the validate parameter's value will be inserted. For example, if the validate parameter in the template is minLength=3 and the validation message is "User name must be at least %s characters" then the corresponding error message would be "User name must be at least 5 characters".
Customizing Validation Messages for BeanEditForm
The BeanEditForm component also supports validation message customizing. The search for messages is similar; the formId is the component id of the BeanEditForm component (not the Form component it contains). The fieldId is the property name.
...
For example, your template may have the following:
Code Block | ||
---|---|---|
| ||
<t:textfield t:id="ssn" validate="required,regexp"/> |
And your message catalog can contain:
Code Block | ||
---|---|---|
| ||
ssn-regexp=\d{3}-\d{2}-\d{4} ssn-regexp-message=Social security numbers are in the format 12-34-5678. |
This technique also works with the BeanEditForm; as with validation messages, the formId is the BeanEditForm component's id, and the fieldId is the name of the property being editted.
...
Lists of validators can be combined into validation macros. This mechanism is convenient for ensuring consistent validation rules across an application. To create a validation macro, just contribute to the ValidatorMacro Service in your module class (normally AppModule.java), by adding a new entry to the configuration object, as shown below. The first parameter is the name of your macro, the second is a comma-separated list of validators:
Code Block | ||
---|---|---|
| ||
@Contribute(ValidatorMacro.class) public static void combinePasswordValidators(MappedConfiguration<String, String> |
...
configuration) { configuration.add("password","required,minlength=5,maxlength=15,"); } |
Then, you can use this new macro in component templates and classes:
Code Block | ||
---|---|---|
| ||
<input t:type="textField" t:id="password" t:validate="password" /> |
Code Block | ||
---|---|---|
| ||
@Validate("password") private String password; |
Overriding the Translator with Events
...
For example, you may have a quantity field that you wish to display as blank, rather than zero, initially:
Code Block | ||
---|---|---|
| ||
<t:textfield t:id="quantity" size="10"/> . . . private int quantity; String onToClientFromQuantity() { if (quantity == 0) |
...
return "";
return null;
}
|
This is good so far, but if the field is optional and the user submits the form, you'll get a validation error, because the empty string is not valid as an integer.
That's where the "parseclient" event comes in:
Code Block | ||
---|---|---|
| ||
Object onParseClientFromQuantity(String input) { if ("".equals(input)) return 0; return null; } |
The event handler method has precedence over the translator. Here it checks for the empty string (and note that the input may be null!) and evaluates that as zero.
...
Now, what if you want to perform your own custom validation? That's another event: "validate":
Code Block | ||
---|---|---|
| ||
void onValidateFromCount(Integer value) throws ValidationException { if (value.equals(13)) throw new ValidationException("Thirteen is an unlucky number."); } |
This event gets fired after the normal validators. It is passed the parsed value (not the string from the client, but the object value from the translator, or from the "parseclient" event handler).
...