Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added table of form events, some wordsmithing

...

Finally, Tapestry is able to not only present the errors back to the user, but to decorate the fields and the labels for the fields, marking them as containing errors (primarily, using CSS effects).

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.

Form Events

The Form component generates emits a number of component events that you may . You'll need to provide event handler methods for some of these.

When rendering, the Form component emits two notifications: first, "prepareForRender", then "prepare". These allow the Form's container to setup any fields or properties that will be referenced in the form. For example, this is a good place to create a temporary entity object to be rendered, or to load an entity from a database to be edited.

...

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 a chance to perform cross-form validation that can't be described declaratively.

...

Next, the Form determines if there have been any validation errors. If there have been, then the submission is considered a failure, and a "failure" event is emitted. If there have been no validation errors, then a "success" event is emitted.

LastFinally, the Form emits a "submit" event (, for logic that doesn't care about success or failure).

Tracking Validation Errors

Associated with the Form is a ValidationTracker that tracks all the provided user input and validation errors for every field in the form. The tracker can be provided to the Form via the Form's tracker parameter, but this is rarely necessary.

The Form includes methods isValid() and getHasErrors(), which are used to see if the Form's validation tracker contains any errors.

In your own logic, it is possible to record your own errors. Form includes two different versions of method recordError(), one of which specifies a Field (an interface implemented by all form element components), and one of which is for "global" errors, unassociated with any particular field.

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}

As with other action requests, the result of a form submission is to send a redirect to the client, which results in a second request (to re-render the page). The ValidationTracker must be persisted (generally in the HttpSession) across these two requests in order to prevent the loss of validation information. Fortunately, the default ValidationTracker provided by the Form component is persistent, so you don't normally have to worry about it.

However, for the same reason, the individual fields updated by the components should also be persisted across requests, and this is something you do need to do yourself – generally with the @Persist annotation.

Form Event (in order)

Phase

When emitted

Typical use

prepareForRender

Render

Before rendering the form

Load an entity from a database to be edited

prepare

Render

Before rendering the form, but after prepareForRender

 

prepareForSubmit

Submit

Before the submitted form is processed

 

prepare

Submit

Before the submitted form is processed, but after prepareForSubmit

 

validate

Submit

After fields have been populated from submitted values and validated

Perform cross-field validation

validateForm

Submit

same as validate

deprecated

failure

Submit

After one or more validation errors have occurred

 

success

Submit

When validation has completed without any errors

Save changes to the database

submit

Submit

After all validation (success or failure) has finished

 

Note that the "prepare" event is emitted during both form rendering and form submission.

Tracking Validation Errors

Associated with the Form is a ValidationTracker that tracks all the provided user input and validation errors for every field in the form. The tracker can be provided to the Form via the Form's tracker parameter, but this is rarely necessary.

The Form includes methods isValid() and getHasErrors(), which are used to see if the Form's validation tracker contains any errors.

In your own logic, it is possible to record your own errors. Form includes two different versions of method recordError(), one of which specifies a Field (an interface implemented by all form element components), and one of which is for "global" errors, unassociated with any particular field.

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}

As with other action requests, the result of a form submission (except when using Zones) is to send a redirect to the client, which results in a second request (to re-render the page). The ValidationTracker must be persisted (generally in the HttpSession) across these two requests in order to prevent the loss of validation information. Fortunately, the default ValidationTracker provided by the Form component is persistent, so you don't normally have to worry about it.

However, for the same reason, the individual fields updated by the components should also be persisted across requests, and this is something you do need to do yourself – generally with the @Persist annotation.

For example, a Login page, which collects a user name and a password, might look like:

...

Finally, notice how business logic fits into validation. The UserAuthenticator service is responsible for ensuring that the userName and (plaintext) password are valid. When it returns false, we ask the Form component to record an error. We provide the PasswordField instance as the first parameter; this ensures that the password field, and its label, are decorated when the Form is re-rendered, to present the errors to the user.

Configuring Fields and Labels

The template for the Login page contains a minimal amount of Tapestry instrumentation:

...

The validate parameter was placed within the Tapestry namespace using the t: prefix. This is not strictly necessary, as the template is well formed either way. However, putting the Tapestry specific values into the Tapestry namespace ensures that the template will itself be valid.

Errors and Decorations

Note: This section has not been updated to reflect the introduction of client-side input validation.

...

This is nice and seamless; the same look and feel and behavior for both the built-in validators, and for errors generated based on application logic.

...

Form Validation

...

The @Validate annotation can take the place of the validate parameter of TextField, PasswordField, TextArea and other components. When the validate parameter is not bound, the component will check for the @Validate annotation and use its value as the validation definition.

The annotation may be placed on the getter or setter method, or on the field itself.

Customizing Validation Messages

Each validator (such as "required" or "minlength") has a default message used (on the client side and the server side) when the constraint is violated; that is, when the user input is not valid.

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.

The first key checked is formId-fieldId-validatorName-message.

  • formId: the local component id of the Form component
  • fieldId: the local component id of the field (TextField, etc.)
  • validatorName: the name of the validator, i.e., "required" or "minlength"
    If there is not 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.

Customizing Validation Messages / BeanEditForm

The BeanEditForm component also supports validation message customizing. The search is the similar; the formId is the component id of the BeanEditForm component (not the Form component it contains). The fieldId is the property name.

Configuring Validator Contraints in the Message Catalog

It is possible to omit the validation constraint from the validator parameter (or @Validator annotation), in which case it is expected to be stored in the message catalog.

This is useful when the validation constraint is awkward to enter inline, such as a regular expression for use with the regexp validator.

The key here is similar to customizing the validation message: formId-fieldId-validatorName or just fieldId-validatorName.

For example, your template may have the following:

...


  <t:textfield t:id="ssn" validate="required,regexp"/>

And your message catalog can contain:

...


ssn-regexp=\d{3}-\d{2}-\d{4}
ssn-regexp-message=Social security numbers are in the format 12-34-5678.

Available Validators

Tapestry provides the following built-in validators:

Validator

Constraint Type

Description

Example

email

Ensures that the given input is a valid e-mail address

<t:textfield value="email" validate="email" />

max

long

Enforces a maximum integer value

<t:textfield value="age" validate="max=120,min=0" />

maxLength

int

Makes sure that a string value has a maximum length

<t:textfield value="zip" validate="maxlength=7" />

min

long

Enforces a minimum integer value

<t:textfield value="age" validate="max=120,min=0" />

minLength

int

Does nothing (used to override a @Validate annotation)

<t:textfield value="somefield" validate="none" />

none

Makes sure that a string value has a minimum length

<t:textfield value="somefield" validate="minlength=1" />

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="27bb6d25-e0ec-480b-8aa2-72e6aba0068a"><ac:plain-text-body><![CDATA[

regexp

pattern

Makes sure that a string value conforms to a given pattern

<t:textfield value="letterfield" validate="regexp=^[A-Za-z]+$" />

]]></ac:plain-text-body></ac:structured-macro>

required

Makes sure that a string value is not null and not the empty string

<t:textfield value="name" validate="required" />

Centralizing Validation with @Validate

The @Validate annotation can take the place of the validate parameter of TextField, PasswordField, TextArea and other components. When the validate parameter is not bound, the component will check for the @Validate annotation and use its value as the validation definition.

The annotation may be placed on the getter or setter method, or on the field itself.

Customizing Validation Messages

Each validator (such as "required" or "minlength") has a default message used (on the client side and the server side) when the constraint is violated; that is, when the user input is not valid.

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.

The first key checked is formId-fieldId-validatorName-message.

  • formId: the local component id of the Form component
  • fieldId: the local component id of the field (TextField, etc.)
  • validatorName: the name of the validator, i.e., "required" or "minlength"
    If there is not 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.

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.

Configuring Validator Contraints in the Message Catalog

It is possible to omit the validation constraint from the validate parameter (or @Validator annotation), in which case it is expected to be stored in the message catalog.

This is useful when the validation constraint is awkward to enter inline, such as a regular expression for use with the regexp validator.

The key here is similar to customizing the validation message: formId-fieldId-validatorName or just fieldId-validatorName.

For example, your template may have the following:

Code Block
html
html

  <t:textfield t:id="ssn" validate="required,regexp"/>

And your message catalog can contain:

Code Block
java
java

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.

Validation Macros

Since
since5.2

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)

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.

Available Validators

Currently Tapestry provides the following built-in validators:

Validator

Constraint Type

Description

Example

email

Ensures that the given input is a valid e-mail address

<t:textfield value="email" validate="email" />

max

long

Enforces a maximum integer value

<t:textfield value="age" validate="max=120,min=0" />

maxLength

int

Makes sure that a string value has a maximum length

<t:textfield value="zip" validate="maxlength=7" />

min

long

Enforces a minimum integer value

<t:textfield value="age" validate="max=120,min=0" />

minLength

int

Does nothing (used to override a @Validate annotation)

<t:textfield value="somefield" validate="none" />

none

Makes sure that a string value has a minimum length

<t:textfield value="somefield" validate="minlength=1" />

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4db82bb1-a040-4f8f-a680-612adeb0e395"><ac:plain-text-body><![CDATA[

regexp

pattern

Makes sure that a string value conforms to a given pattern

<t:textfield value="letterfield" validate="regexp=^[A-Za-z]+$" />

]]></ac:plain-text-body></ac:structured-macro>

required

Makes sure that a string value is not null and not the empty string

<t:textfield value="name" validate="required" />

Validation Macros

Since Tapestry 5.2, we can create validation macros, wich will contain a list of validators. This mechanism is very useful for combining your validators. We just have to contribute to the ValidatorMacro Service in your AppModule, 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
java
java
@Contribute(ValidatorMacro.class)
public static void combinePasswordValidators(MappedConfiguration<String, String> configuration) {
      configuration.add("password","required,minlength=5,maxlength=15,");
}

Then, we you can use this new macro in our Template or Java Class.component templates and classes:

Code Block
html
html
<input t:type="textField" t:id="password" t:validate="password" />
Code Block
java
java
@Validate("password")
private String password;

Overriding the Translator with Events

The TextField, PasswordField and TextArea components all have a translate parameter, a FieldTranslator object that is used to convert values on the server side to strings on the client side.

...