net.sf.click.control
Class Form

java.lang.Object
  extended bynet.sf.click.control.AbstractControl
      extended bynet.sf.click.control.AbstractContainer
          extended bynet.sf.click.control.Form
All Implemented Interfaces:
Container, Control, Serializable

public class Form
extends AbstractContainer

Provides a Form control:   <form method='post'>.

*
*
 
When a Form is processed it will process its Field controls in the order they were added to the form, and then it will process the Button controls in the added order. Once all the Fields have been processed the form will invoke its action listener if defined.

Form Example

The example below illustrates a Form being used in a login Page.
 public class Login extends Page {

     public Form form = new Form();

     public Login() {
         form.add(new TextField("username", true));
         form.add(new PasswordField("password", true));
         form.add(new Submit("ok", "  OK  ", this, "onOkClick"));
         form.add(new Submit("cancel", this, "onCancelClick"));
     }

     public boolean onOkClick() {
         if (form.isValid()) {
             User user = new User();
             form.copyTo(user);

             if (getUserService().isAuthenticatedUser(user)) {
                 getContext().setSessionAttribute("user", user);
                 setRedirect(HomePage.class);
             }
             else {
                 form.setError(getMessage("authentication-error"));
             }
         }
         return true;
     }

     public boolean onCancelClick() {
         setRedirect(WelcomePage.class);
         return false;
     }
 } 
The forms corresponding template code is below. Note the form automatically renders itself when Velocity invokes its AbstractContainer.toString() method.
 $form 
If a Form has been posted and processed, if it has an error defined or any of its Fields have validation errors they will be automatically rendered, and the isValid() method will return false.

Data Binding

To bind value objects to a forms fields use the copy methods: To debug the data binding being performed, use the Click application mode to "debug" or use the debug copy methods.

Binding of nested data objects is supported using the OGNL library. To use nested objects in your form, simply specify the object path as the Field name. Note in the object path you exclude the root object, so the path customer.address.state is specified as address.state.

For example:

 // The customer.address.state field
 TextField stateField = new TextField("address.state");
 form.add(stateField);
 ..

 // Loads the customer address state into the form stateField
 Customer customer = getCustomer();
 form.copyFrom(customer);
 ..

 // Copies form stateField value into the customer address state
 Customer customer = new Customer();
 form.copyTo(customer); 
When populating an object from a form post Click will automatically create any null nested objects so their properties can be set. To do this Click uses the no-args constructor of the nested objects class.

copyTo(Object) and copyFrom(Object) also supports java.util.Map as an argument. Examples of using java.util.Map are shown in the respective method descriptions.

Form Validation

The Form control supports automatic field validation. By default when a POST request is made the form will validate the field values. To disable automatic validation set setValidate(boolean) to false.

Form validate() method provides special validation for multipart requests. Multipart requests are used when uploading files from the client.

The validate() method checks that files being uploaded do not exceed the maximum request size or the maximum file size.

Please note that if the maximum request size or maximum file size is exceeded, the request is deemed invalid and no further processing is performed on the form or fields. Instead the form will display the appropriate error message for the invalid request. See validate() for details of the error message properties.

JavaScript Validation

The Form control also supports client side JavaScript validation. By default JavaScript validation is not enabled. To enable JavaScript validation set setJavaScriptValidation(boolean) to true. For example:

 Form form = new Form("form");
 form.setJavaScriptValidation(true);

 // Add form fields
 ..

 form.add(new Submit("ok", " OK ", this, "onOkClicked");

 Submit cancel = new Submit("cancel", "Cancel", this, "onCancelClicked");
 cancel.setCancelJavaScriptValidation(true);

 addControl(form); 
Please note in that is this example the cancel submit button has Submit.setCancelJavaScriptValidation(boolean) set to true. This prevents JavaScript form validation being performed when the cancel button is clicked.

CSS and JavaScript Imports

The Form control automatically deploys the control CSS style sheet (control.css) and JavaScript file (control.js) to the application directory /click. To import these files and any form control imports simply reference $cssImports and $jsImports in the page template. For example:
 <html>
 <head>
 $cssImports
 </head>
 <body>
 $form
 </body>
 </html>
 $jsImports

Form Layout

The Form control supports rendering using automatic and manual layout techniques.

Auto Layout

If you include a form variable in your template the form will be automatically laid out and rendered. Auto layout, form and field rendering options include:
buttonAlign button alignment:   ["left", "center", "right"]
buttonStyle button <td> "style" attribute value
columns number of form table columns, the default value number is 1
errorsAlign validation error messages alignment:   ["left", "center", "right"]
errorsPosition validation error messages position:   ["top", "middle", "bottom"]
errorsStyle errors <td> "style" attribute value
fieldStyle field <td> "style" attribute value
labelAlign field label alignment:   ["left", "center", "right"]
labelsPosition label position relative to field:   ["left", "top"]
labelStyle label <td> "style" attribute value
click/control.css control CSS styles, automatically deployed to the click web directory
/click-control.properties form and field messages and HTML, located under classpath

Manual Layout

You can also manually layout the Form in the page template specifying the fields using the named field notation:
 $form.fields.usernameField 
Whenever including your own Form markup in a page template or Velocity macro always specify: The hidden field is used by Click to determine which form was posted on a page which may contain multiple forms.

Alternatively you can use the Form startTag() and endTag() methods to render this information.

An example of a manually layed out Login form is provided below:

 $form.startTag()

   <table style="margin: 1em;">

     #if ($form.error)
     <tr>
       <td colspan="2" style="color: red;"> $form.error </td>
     </tr>
     #end
     #if ($form.fields.usernameField.error)
     <tr>
       <td colspan="2" style="color: red;"> $form.fields.usernameField.error </td>
     </tr>
     #end
     #if ($form.fields.passwordField.error)
     <tr>
       <td colspan="2" style="color: red;"> $form.fields.passwordField.error </td>
     </tr>
     #end

     <tr>
       <td> Username: </td>
       <td> $form.fields.usernameField </td>
     </tr>
     <tr>
       <td> Password: </td>
       <td> $form.fields.passwordField </td>
     </tr>

     <tr>
       <td>
         $form.fields.okSubmit
         $form.fields.cancelSubmit
       </td>
     </tr>

   </table>

 $form.endTag() 
As you can see in this example most of the code and markup is generic and could be reused. This is where Velocity Macros come in.

Velocity Macros

Velocity Macros (velocimacros) are a great way to encapsulate customized forms.

To create a generic form layout you can use the Form getFieldList() and getButtonList() properties within a Velocity macro. If you want to access all Form Controls from within a Velocity template or macro use AbstractContainer.getControls().

The example below provides a generic writeForm() macro which you could use through out an application. This Velocity macro code would be contained in a macro file, e.g. macro.vm.

 #* Custom Form Macro Code *#
 #macro( writeForm[$form] )

 $form.startTag()

 <table width="100%">

 #if ($form.error)
   <tr>
     <td colspan="2" style="color: red;"> $form.error </td>
   </tr>
 #end

 #foreach ($field in $form.fieldList)
   #if (!$field.hidden)
     #if (!$field.valid)
     <tr>
       <td colspan="2"> $field.error </td>
     </tr>
     #end

   <tr>
     <td> $field.label: </td><td> $field </td>
   </tr>
   #end
 #end

  <tr>
    <td colspan="2">
    #foreach ($button in $form.buttonList)
      $button &nbsp;
    #end
    </td>
  </tr>

 </table>

 $form.endTag()

 #end 
You would then call this macro in your Page template passing it your form object:
 #writeForm($form) 
At render time Velocity will execute the macro using the given form and render the results to the response output stream.

Configuring Macros

To configure your application to use your macros you can:

Preventing Accidental Form Posts

Users may accidentally make multiple form submissions by refreshing a page or by pressing the back button.

To prevent multiple form posts from page refreshes use the Post Redirect pattern. With this pattern once the user has posted a form you redirect to another page. If the user then presses the refresh button, they will making a GET request on the current page. Please see the Redirect After Post article for more information on this topic.

To prevent multiple form posts from use of the browser back button use one of the Form onSubmitCheck(net.sf.click.Page, String) methods. For example:

 public class Purchase extends Page {
     ..

     public boolean onSecurityCheck() {
         return form.onSubmitCheck(this, "/invalid-submit.html");
     }
 } 
The form submit check methods store a special token in the users session and in a hidden field in the form to ensure a form post isn't replayed.

 

See also the W3C HTML reference: FORM

Author:
Malcolm Edgar
See Also:
Field, Submit, Serialized Form

Field Summary
protected  String actionURL
          The form action URL.
static String ALIGN_CENTER
          The align center, form layout constant:   "center".
static String ALIGN_LEFT
          The align left, form layout constant:   "left".
static String ALIGN_RIGHT
          The align right, form layout constant:   "right".
protected  String buttonAlign
          The button align, default value is "left".
protected  List buttonList
          The ordered list of button values.
protected  String buttonStyle
          The button <td> "style" attribute value.
protected  int columns
          The number of form layout table columns, default value: 1.
protected  int defaultFieldSize
          The default field size, default value: 0.
protected  boolean disabled
          The form disabled value.
protected  String enctype
          The form "enctype" attribute.
protected  String error
          The form level error message.
protected  String errorsAlign
          The errors block align, default value is "left".
protected  String errorsPosition
          The form errors position ["top", "middle", "bottom"] default value:   "top".
protected  String errorsStyle
          The error <td> "style" attribute value.
protected  List fieldList
          The ordered list of fields, excluding buttons.
protected  String fieldStyle
          The field <td> "style" attribute value.
protected  Map fieldWidths
          The map of field width values.
protected static String FOCUS_JAVASCRIPT
          The Form set field focus JavaScript.
static String FORM_NAME
          The form name parameter for multiple forms:   "form_name".
protected static String HTML_IMPORTS
          The HTML imports statements.
protected  boolean javaScriptValidation
          The JavaScript client side form fields validation flag.
protected  String labelAlign
          The label align, default value is "left".
protected  String labelsPosition
          The form labels position ["left", "top"] default value:   "left".
protected  String labelStyle
          The label <td> "style" attribute value.
protected  String method
          The form method ["post, "get"], default value:   post.
static String MULTIPART_FORM_DATA
          The HTTP content type header for multipart forms.
static String POSITION_BOTTOM
          The position bottom, errors on bottom form layout constant:   "top".
static String POSITION_LEFT
          The position left, labels of left form layout constant:   "left".
static String POSITION_MIDDLE
          The position middle, errors in middle form layout constant:   "middle".
static String POSITION_TOP
          The position top, errors and labels form layout constant:   "top".
protected  boolean readonly
          The form is readonly flag.
static String SUBMIT_CHECK
          The submit check reserved request parameter prefix:   SUBMIT_CHECK_.
protected  boolean validate
          The form validate fields when processing flag.
 
Fields inherited from class net.sf.click.control.AbstractContainer
controlMap, controls
 
Fields inherited from class net.sf.click.control.AbstractControl
actionListener, attributes, listener, listenerMethod, messages, name, parent, styles
 
Fields inherited from interface net.sf.click.Control
CONTROL_MESSAGES
 
Constructor Summary
Form()
          Create a form with no name.
Form(String name)
          Create a form with the given name.
 
Method Summary
 Control add(Control control)
          Add a Control to the form and return the added instance.
 Control add(Control control, int width)
          Add the control to the form and specify the control's width in columns.
 Field add(Field field)
          Add the field to the form, and set the fields form property.
 Field add(Field field, int width)
          Add the field to the form and specify the field's width in columns.
 void clearErrors()
          Clear any form or field errors by setting them to null.
 void clearValues()
          Clear all the form field values setting them to null.
 void copyFrom(Object object)
          Copy the given object's attributes into the Form's field values.
 void copyFrom(Object object, boolean debug)
          Copy the given object's attributes into the Form's field values.
 void copyTo(Object object)
          Copy the Form's field values into the given object's attributes.
 void copyTo(Object object, boolean debug)
          Copy the Form's field values into the given object's attributes.
 String endTag()
          Return the rendered form end tag and JavaScript for field focus and validation.
 String getActionURL()
          Return the form "action" attribute URL value.
 String getButtonAlign()
          Return the buttons <td> HTML horizontal alignment: "left", "center", "right".
 List getButtonList()
          Return the ordered list of Buttons.
 String getButtonStyle()
          Return the button <td> "style" attribute value.
 int getColumns()
          Return the number of form layout table columns.
 int getControlSizeEst()
          Return the estimated rendered control size in characters.
 int getDefaultFieldSize()
          Return the form default field size.
 String getEnctype()
          Return the form "enctype" attribute value, or null if not defined.
 String getError()
          Return the form level error message.
 List getErrorFields()
          Return a list of form fields which are not valid, not hidden and not disabled.
 String getErrorsAlign()
          Return the errors block HTML horizontal alignment: "left", "center", "right".
 String getErrorsPosition()
          Return the form errors position ["top", "middle", "bottom"].
 String getErrorsStyle()
          Return the error <td> "style" attribute value.
 Field getField(String name)
          Return the named field if contained in the form or null if not found.
 List getFieldList()
          Return the ordered list of form fields, excluding buttons.
 Map getFields()
          Return the Map of form fields (including buttons), keyed on field name.
 String getFieldStyle()
          Return the field <td> "style" attribute value.
 String getFieldValue(String name)
          Return the field value for the named field, or null if the field is not found.
 Map getFieldWidths()
          Return the map of field width values, keyed on field name.
protected  int getFormSizeEst(List formFields)
          Return the estimated rendered form size in characters.
 String getHtmlImports()
          Return the HTML head import statements for the CSS stylesheet (click/control.css) and JavaScript (click/control.js) files.
 boolean getJavaScriptValidation()
          Return true if JavaScript client side form validation is enabled.
 String getLabelAlign()
          Return the field label HTML horizontal alignment: "left", "center", "right".
 String getLabelsPosition()
          Return the form labels position ["left", "top"].
 String getLabelStyle()
          Return the label <td> "style" attribute value.
 String getMethod()
          Return the form method ["post" | "get"], default value is post.
 String getTag()
          Return the form's html tag: form.
 boolean getValidate()
          Return true if the Form fields should validate themselves when being processed.
protected  boolean hasPostError()
          Returns true if a POST error occurred, false otherwise.
 Control insert(Control control, int index)
          Add the control to the form at the specified index, and return the added instance.
 boolean isDisabled()
          Return true if the form is a disabled.
 boolean isFormSubmission()
          Return true if the page request is a submission from this form.
 boolean isReadonly()
          Return true if the form is a readonly.
 boolean isValid()
          Return true if the fields are valid and there is no form level error, otherwise return false.
 void onDestroy()
          Destroy the controls contained in the Form and clear any form error message.
 boolean onProcess()
          Process the Form and its child controls only if the Form was submitted by the user.
 boolean onSubmitCheck(Page page, Class pageClass)
          Perform a form submission check ensuring the user has not replayed the form submission by using the browser back button.
 boolean onSubmitCheck(Page page, Object submitListener, String submitListenerMethod)
          Perform a form submission check ensuring the user has not replayed the form submission by using the browser back button.
 boolean onSubmitCheck(Page page, String redirectPath)
          Perform a form submission check ensuring the user has not replayed the form submission by using the browser back button.
protected  boolean performSubmitCheck()
          Perform a back button submit check, returning true if the request is valid or false otherwise.
 boolean remove(Control control)
          Remove the given control from the container, returning true if the control was found in the container and removed, or false if the control was not found.
 boolean removeField(String name)
          Remove the named field from the form, returning true if removed or false if not found.
 void removeFields(List fieldNames)
          Remove the list of named fields from the form.
 void render(HtmlStringBuffer buffer)
          Render the HTML representation of the Form.
protected  void renderButtons(HtmlStringBuffer buffer)
          Render the given list of Buttons to the string buffer.
protected  void renderControls(HtmlStringBuffer buffer, Container container, List controls, Map fieldWidths, int columns)
          Render the specified controls of the container to the string buffer.
protected  void renderErrors(HtmlStringBuffer buffer, boolean processed)
          Render the form errors to the given buffer is form processed.
protected  void renderFields(HtmlStringBuffer buffer)
          Render the non hidden Form Fields to the string buffer.
protected  void renderFocusJavaScript(HtmlStringBuffer buffer, List formFields)
          Render the Form field focus JavaScript to the string buffer.
protected  void renderHeader(HtmlStringBuffer buffer, List formFields)
          Render the given form start tag and the form hidden fields to the given buffer.
protected  void renderTagEnd(List formFields, HtmlStringBuffer buffer)
          Close the form tag and render any additional content after the Form.
protected  void renderValidationJavaScript(HtmlStringBuffer buffer, List formFields)
          Render the Form validation JavaScript to the string buffer.
 void setActionURL(String value)
          Return the form "action" attribute URL value.
 void setButtonAlign(String align)
          Set the button <td> HTML horizontal alignment: "left", "center", "right".
 void setButtonStyle(String value)
          Set the button <td> "style" attribute value.
 void setColumns(int columns)
          Set the number of form layout table columns.
 void setDefaultFieldSize(int size)
          Return the form default field size.
 void setDisabled(boolean disabled)
          Set the form disabled flag.
 void setEnctype(String enctype)
          Set the form "enctype" attribute value.
 void setError(String error)
          Set the form level validation error message.
 void setErrorsAlign(String align)
          Set the errors block HTML horizontal alignment: "left", "center", "right".
 void setErrorsPosition(String position)
          Set the form errors position ["top", "middle", "bottom"].
 void setErrorsStyle(String value)
          Set the errors <td> "style" attribute value.
 void setFieldStyle(String value)
          Set the field <td> "style" attribute value.
 void setJavaScriptValidation(boolean validate)
          Set the JavaScript client side form validation flag.
 void setLabelAlign(String align)
          Set the field label HTML horizontal alignment: "left", "center", "right".
 void setLabelsPosition(String position)
          Set the form labels position ["left", "top"].
 void setLabelStyle(String value)
          Set the label <td> "style" attribute value.
 void setListener(Object listener, String method)
          The callback listener will only be called during processing if the field value is valid.
 void setMethod(String value)
          Set the form method ["post" | "get"].
 void setName(String name)
          Set the name of the form.
 void setReadonly(boolean readonly)
          Set the form readonly flag.
 void setValidate(boolean validate)
          Set the Form field validation flag, telling the Fields to validate themselves when their onProcess() method is invoked.
 String startTag()
          Return the rendered opening form tag and all the forms hidden fields.
 void validate()
          Validate the Form request submission.
 
Methods inherited from class net.sf.click.control.AbstractContainer
contains, getControl, getControlMap, getControls, hasControls, onInit, onRender, renderChildren, renderContent, renderTagEnd, toString
 
Methods inherited from class net.sf.click.control.AbstractControl
addStyleClass, appendAttributes, getActionListener, getAttribute, getAttributes, getContext, getId, getMessage, getMessage, getMessage, getMessages, getName, getPage, getParent, getStyle, getStyles, hasAttribute, hasAttributes, hasStyles, onDeploy, registerActionEvent, removeStyleClass, renderTagBegin, setActionListener, setAttribute, setId, setParent, setStyle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface net.sf.click.Control
getContext, getId, getMessages, getName, getParent, onDeploy, setParent
 

Field Detail

ALIGN_LEFT

public static final String ALIGN_LEFT
The align left, form layout constant:   "left".

See Also:
Constant Field Values

ALIGN_CENTER

public static final String ALIGN_CENTER
The align center, form layout constant:   "center".

See Also:
Constant Field Values

ALIGN_RIGHT

public static final String ALIGN_RIGHT
The align right, form layout constant:   "right".

See Also:
Constant Field Values

POSITION_TOP

public static final String POSITION_TOP
The position top, errors and labels form layout constant:   "top".

See Also:
Constant Field Values

POSITION_MIDDLE

public static final String POSITION_MIDDLE
The position middle, errors in middle form layout constant:   "middle".

See Also:
Constant Field Values

POSITION_BOTTOM

public static final String POSITION_BOTTOM
The position bottom, errors on bottom form layout constant:   "top".

See Also:
Constant Field Values

POSITION_LEFT

public static final String POSITION_LEFT
The position left, labels of left form layout constant:   "left".

See Also:
Constant Field Values

FOCUS_JAVASCRIPT

protected static final String FOCUS_JAVASCRIPT
The Form set field focus JavaScript.

See Also:
Constant Field Values

FORM_NAME

public static final String FORM_NAME
The form name parameter for multiple forms:   "form_name".

See Also:
Constant Field Values

MULTIPART_FORM_DATA

public static final String MULTIPART_FORM_DATA
The HTTP content type header for multipart forms.

See Also:
Constant Field Values

SUBMIT_CHECK

public static final String SUBMIT_CHECK
The submit check reserved request parameter prefix:   SUBMIT_CHECK_.

See Also:
Constant Field Values

HTML_IMPORTS

protected static final String HTML_IMPORTS
The HTML imports statements.

See Also:
Constant Field Values

actionURL

protected String actionURL
The form action URL.


disabled

protected boolean disabled
The form disabled value.


enctype

protected String enctype
The form "enctype" attribute.


error

protected String error
The form level error message.


fieldList

protected final List fieldList
The ordered list of fields, excluding buttons.


method

protected String method
The form method ["post, "get"], default value:   post.


readonly

protected boolean readonly
The form is readonly flag.


validate

protected boolean validate
The form validate fields when processing flag.


buttonAlign

protected String buttonAlign
The button align, default value is "left".


buttonList

protected final List buttonList
The ordered list of button values.


buttonStyle

protected String buttonStyle
The button <td> "style" attribute value.


columns

protected int columns
The number of form layout table columns, default value: 1.

This property is used to layout the number of table columns the form is rendered with using a flow layout style.


defaultFieldSize

protected int defaultFieldSize
The default field size, default value: 0.

If the form default field size is greater than 0, when fields are added to the form the field's size will be set to the default value.


errorsAlign

protected String errorsAlign
The errors block align, default value is "left".


errorsPosition

protected String errorsPosition
The form errors position ["top", "middle", "bottom"] default value:   "top".


errorsStyle

protected String errorsStyle
The error <td> "style" attribute value.


fieldStyle

protected String fieldStyle
The field <td> "style" attribute value.


fieldWidths

protected Map fieldWidths
The map of field width values.


javaScriptValidation

protected boolean javaScriptValidation
The JavaScript client side form fields validation flag. By default JavaScript validation is not enabled.


labelAlign

protected String labelAlign
The label align, default value is "left".


labelsPosition

protected String labelsPosition
The form labels position ["left", "top"] default value:   "left".


labelStyle

protected String labelStyle
The label <td> "style" attribute value.

Constructor Detail

Form

public Form(String name)
Create a form with the given name.

Parameters:
name - the name of the form
Throws:
IllegalArgumentException - if the form name is null

Form

public Form()
Create a form with no name.

Please note the control's name must be defined before it is valid.

Method Detail

add

public Control add(Control control)
Add a Control to the form and return the added instance.

Controls can be retrieved from the Map controlMap where the key is the Control name and value is the Control instance.

All controls are available on the controls list in the order they were added. If you are only interested in Fields, note that Buttons are available on the buttonList while other fields are available on fieldList.

Specified by:
add in interface Container
Overrides:
add in class AbstractContainer
Parameters:
control - the control to add to the container and return
Returns:
the control that was added to the container
Throws:
IllegalArgumentException - if the control is null, the Control name is not defined or the container already contains a control with the same name
See Also:
Container.add(net.sf.click.Control)

insert

public Control insert(Control control,
                      int index)
Add the control to the form at the specified index, and return the added instance.

Controls can be retrieved from the Map controlMap where the key is the Control name and value is the Control instance.

All controls are available on the controls list at the index they were inserted. If you are only interested in Fields, note that Buttons are available on the buttonList while other fields are available on fieldList.

The specified index only applies to controls, not buttonList or fieldList.

Please note if the specified control already has a parent assigned, it will automatically be removed from that parent and inserted into the form.

Also note: Form automatically adds hidden fields to preserve state across requests. Be aware of this when using insert as the hidden fields might influence the position of the Control you insert. This restriction might be removed in a future version of Click.

Specified by:
insert in interface Container
Overrides:
insert in class AbstractContainer
Parameters:
control - the control to add to the container
index - the index at which the control is to be inserted
Returns:
the control that was added to the container
Throws:
IllegalArgumentException - if the control is null or if the control and container is the same instance or the container already contains a control with the same name or if the Field name is not defined
IndexOutOfBoundsException - if index is out of range (index < 0 || index > getControls().size())
See Also:
Container.insert(net.sf.click.Control, int)

add

public Field add(Field field)
Add the field to the form, and set the fields form property.

Fields can be retrieved from the Map fields where the key is the Field name and value is the Field instance.

Buttons are available on the buttonList while other fields are available on fieldList.

Parameters:
field - the field to add to the form
Returns:
the field added to this form
Throws:
IllegalArgumentException - if the field is null, the field name is not defined or the form already contains a control with the same name
See Also:
add(net.sf.click.Control)

add

public Field add(Field field,
                 int width)
Add the field to the form and specify the field's width in columns.

Fields can be retrieved from the Map fields where the key is the Field name and value is the Field instance.

Fields are available on fieldList.

Note Button and HiddenField types are not valid arguments for this method.

Parameters:
field - the field to add to the form
width - the width of the field in table columns
Returns:
the field added to this form
Throws:
IllegalArgumentException - if the field is null, field name is not defined, field is a Button or HiddenField, the form already contains a field with the same name or the width < 1
See Also:
add(net.sf.click.Control)

add

public Control add(Control control,
                   int width)
Add the control to the form and specify the control's width in columns.

Controls can be retrieved from the Map controlMap where the key is the Control name and value is the Control instance.

Controls are available on the controls list.

Note Button and HiddenField types are not valid arguments for this method.

Parameters:
control - the control to add to the form
width - the width of the control in table columns
Returns:
the control added to this form
Throws:
IllegalArgumentException - if the control is null, control is a Button or HiddenField, the form already contains a control with the same name or the width < 1
See Also:
add(net.sf.click.Control)

remove

public boolean remove(Control control)
Description copied from interface: Container
Remove the given control from the container, returning true if the control was found in the container and removed, or false if the control was not found.

Specified by:
remove in interface Container
Overrides:
remove in class AbstractContainer
Parameters:
control - the control to remove from the container
Returns:
true if the control was removed from the container
Throws:
IllegalArgumentException - if the control is null
See Also:
Container.remove(net.sf.click.Control)

removeField

public boolean removeField(String name)
Remove the named field from the form, returning true if removed or false if not found.

Parameters:
name - the name of the field to remove from the form
Returns:
true if the named field was removed or false otherwise

removeFields

public void removeFields(List fieldNames)
Remove the list of named fields from the form.

Parameters:
fieldNames - the list of field names to remove from the form
Throws:
IllegalArgumentException - if any of the fields is null

getTag

public String getTag()
Return the form's html tag: form.

Overrides:
getTag in class AbstractControl
Returns:
this controls html tag
See Also:
AbstractControl.getTag()

getActionURL

public String getActionURL()
Return the form "action" attribute URL value. If the action URL attribute has not been explicitly set the form action attribute will target the page containing the form. This is the default behaviour for most scenarios. However if you explicitly specify the form "action" URL attribute, this value will be used instead.

Setting the form action attribute is useful for situations where you want a form to submit to a different page. This can also be used to have a form submit to the J2EE Container for authentication, by setting the action URL to "j_security_check".

The action URL will always be encoded by the response to ensure it includes the Session ID if required.

Returns:
the form "action" attribute URL value.

setActionURL

public void setActionURL(String value)
Return the form "action" attribute URL value. By setting this value you will override the default action URL which points to the page containing the form.

Setting the form action attribute is useful for situations where you want a form to submit to a different page. This can also be used to have a form submit to the J2EE Container for authentication, by setting the action URL to "j_security_check".

Parameters:
value - the form "action" attribute URL value

getControlSizeEst

public int getControlSizeEst()
Description copied from class: AbstractControl
Return the estimated rendered control size in characters.

Overrides:
getControlSizeEst in class AbstractContainer
Returns:
the estimated rendered control size in characters
See Also:
AbstractControl.getControlSizeEst()

isDisabled

public boolean isDisabled()
Return true if the form is a disabled.

Returns:
true if the form is a disabled

setDisabled

public void setDisabled(boolean disabled)
Set the form disabled flag.

Parameters:
disabled - the form disabled flag

getEnctype

public String getEnctype()
Return the form "enctype" attribute value, or null if not defined.

Returns:
the form "enctype" attribute value, or null if not defined

setEnctype

public void setEnctype(String enctype)
Set the form "enctype" attribute value.

Parameters:
enctype - the form "enctype" attribute value, or null if not defined

getError

public String getError()
Return the form level error message.

Returns:
the form level error message

setError

public void setError(String error)
Set the form level validation error message. If the error message is not null the form is invalid.

Parameters:
error - the validation error message

getErrorFields

public List getErrorFields()
Return a list of form fields which are not valid, not hidden and not disabled.

Returns:
list of form fields which are not valid, not hidden and not disabled

getField

public Field getField(String name)
Return the named field if contained in the form or null if not found.

Parameters:
name - the name of the field
Returns:
the named field if contained in the form
Throws:
IllegalStateException - if a non-field control is found with the specified name

getFieldValue

public String getFieldValue(String name)
Return the field value for the named field, or null if the field is not found.

Parameters:
name - the name of the field
Returns:
the field value for the named field

getHtmlImports

public String getHtmlImports()
Return the HTML head import statements for the CSS stylesheet (click/control.css) and JavaScript (click/control.js) files.

Specified by:
getHtmlImports in interface Control
Overrides:
getHtmlImports in class AbstractContainer
Returns:
the HTML head import statements for the control stylesheet and JavaScript files
See Also:
Control.getHtmlImports()

getMethod

public String getMethod()
Return the form method ["post" | "get"], default value is post.

Returns:
the form method

setMethod

public void setMethod(String value)
Set the form method ["post" | "get"].

Parameters:
value - the form method

isFormSubmission

public boolean isFormSubmission()
Return true if the page request is a submission from this form.

A form submission requires the following criteria:

Returns:
true if the page request is a submission from this form

setName

public void setName(String name)
Set the name of the form.

Specified by:
setName in interface Control
Overrides:
setName in class AbstractControl
Parameters:
name - of the control
Throws:
IllegalArgumentException - if the name is null
See Also:
Control.setName(String)

isReadonly

public boolean isReadonly()
Return true if the form is a readonly.

Returns:
true if the form is a readonly

setReadonly

public void setReadonly(boolean readonly)
Set the form readonly flag.

Parameters:
readonly - the form readonly flag

isValid

public boolean isValid()
Return true if the fields are valid and there is no form level error, otherwise return false.

Returns:
true if the fields are valid and there is no form level error

getFieldList

public List getFieldList()
Return the ordered list of form fields, excluding buttons.

The order of the fields is the same order they were added to the form.

The returned list includes only fields added directly to the Form.

Returns:
the ordered List of form fields, excluding buttons

getFields

public Map getFields()
Return the Map of form fields (including buttons), keyed on field name.

The returned map includes only fields added directly to the Form.

Returns:
the Map of form fields (including buttons), keyed on field name
See Also:
AbstractContainer.getControlMap()

getValidate

public boolean getValidate()
Return true if the Form fields should validate themselves when being processed.

Returns:
true if the form fields should perform validation when being processed

setValidate

public void setValidate(boolean validate)
Set the Form field validation flag, telling the Fields to validate themselves when their onProcess() method is invoked.

Parameters:
validate - the Form field validation flag

getButtonAlign

public String getButtonAlign()
Return the buttons <td> HTML horizontal alignment: "left", "center", "right".

Returns:
the field label HTML horizontal alignment

setButtonAlign

public void setButtonAlign(String align)
Set the button <td> HTML horizontal alignment: "left", "center", "right". Note the given align is not validated.

Parameters:
align - the field label HTML horizontal alignment

getButtonList

public List getButtonList()
Return the ordered list of Buttons.

The order of the buttons is the same order they were added to the form.

The returned list includes only buttons added directly to the Form.

Returns:
the ordered list of Buttons.

getButtonStyle

public String getButtonStyle()
Return the button <td> "style" attribute value.

Returns:
the button <td> "style" attribute value

setButtonStyle

public void setButtonStyle(String value)
Set the button <td> "style" attribute value.

Parameters:
value - the button <td> "style" attribute value

getColumns

public int getColumns()
Return the number of form layout table columns. This property is used to layout the number of table columns the form is rendered with.

Returns:
the number of form layout table columns

setColumns

public void setColumns(int columns)
Set the number of form layout table columns. This property is used to layout the number of table columns the form is rendered with.

Parameters:
columns - the number of form layout table columns

getDefaultFieldSize

public int getDefaultFieldSize()
Return the form default field size. If the form default field size is greater than 0, when fields are added to the form the field's size will be set to the default value.

Returns:
the form default field size

setDefaultFieldSize

public void setDefaultFieldSize(int size)
Return the form default field size. If the form default field size is greater than 0, when fields are added to the form the field's size will be set to the default value.

Parameters:
size - the default field size

getErrorsAlign

public String getErrorsAlign()
Return the errors block HTML horizontal alignment: "left", "center", "right".

Returns:
the errors block HTML horizontal alignment

setErrorsAlign

public void setErrorsAlign(String align)
Set the errors block HTML horizontal alignment: "left", "center", "right". Note the given align is not validated.

Parameters:
align - the errors block HTML horizontal alignment

getErrorsPosition

public String getErrorsPosition()
Return the form errors position ["top", "middle", "bottom"].

Returns:
form errors position

setErrorsPosition

public void setErrorsPosition(String position)
Set the form errors position ["top", "middle", "bottom"].

Parameters:
position - the form errors position

getErrorsStyle

public String getErrorsStyle()
Return the error <td> "style" attribute value.

Returns:
the error <td> "style" attribute value

setErrorsStyle

public void setErrorsStyle(String value)
Set the errors <td> "style" attribute value.

Parameters:
value - the errors <td> "style" attribute value

getFieldStyle

public String getFieldStyle()
Return the field <td> "style" attribute value.

Returns:
the field <td> "style" attribute value

setFieldStyle

public void setFieldStyle(String value)
Set the field <td> "style" attribute value.

Parameters:
value - the field <td> "style" attribute value

getFieldWidths

public Map getFieldWidths()
Return the map of field width values, keyed on field name.

Returns:
the map of field width values, keyed on field name

getJavaScriptValidation

public boolean getJavaScriptValidation()
Return true if JavaScript client side form validation is enabled.

Returns:
true if JavaScript client side form validation is enabled

setJavaScriptValidation

public void setJavaScriptValidation(boolean validate)
Set the JavaScript client side form validation flag.

Parameters:
validate - the JavaScript client side validation flag

getLabelAlign

public String getLabelAlign()
Return the field label HTML horizontal alignment: "left", "center", "right".

Returns:
the field label HTML horizontal alignment

setLabelAlign

public void setLabelAlign(String align)
Set the field label HTML horizontal alignment: "left", "center", "right". Note the given align is not validated.

Parameters:
align - the field label HTML horizontal alignment

getLabelsPosition

public String getLabelsPosition()
Return the form labels position ["left", "top"].

Returns:
form labels position

setLabelsPosition

public void setLabelsPosition(String position)
Set the form labels position ["left", "top"].

Parameters:
position - the form labels position

getLabelStyle

public String getLabelStyle()
Return the label <td> "style" attribute value.

Returns:
the label <td> "style" attribute value

setLabelStyle

public void setLabelStyle(String value)
Set the label <td> "style" attribute value.

Parameters:
value - the label <td> "style" attribute value

setListener

public void setListener(Object listener,
                        String method)
The callback listener will only be called during processing if the field value is valid. If the field has validation errors the listener will not be called.

Specified by:
setListener in interface Control
Overrides:
setListener in class AbstractControl
Parameters:
listener - the listener object with the named method to invoke
method - the name of the method to invoke
See Also:
Control.setListener(Object, String)

clearErrors

public void clearErrors()
Clear any form or field errors by setting them to null.


clearValues

public void clearValues()
Clear all the form field values setting them to null.


copyFrom

public void copyFrom(Object object)
Copy the given object's attributes into the Form's field values. In other words automatically populate Form's field values with the given objects attributes.

The following example populates the Form field with Customer attributes:

  public void onGet() {
     Long customerId = ..
     Customer customer = CustomerDAO.findByPK(customerId);
     form.copyFrom(customer);
  }
 
copyForm also supports java.util.Map as an argument.

By specifying a map, the Form's field values will be populated by matching key/value pairs. A match occurs when the map's key is equal to a field's name.

The following example populates the Form fields with a map's key/value pairs:

  public void onInit() {
     form = new Form("form");
     form.add(new TextField("name"));
     form.add(new TextField("address.street"));
  }

  public void onGet() {
     Map map = new HashMap();
     map.put("name", "Steve");
     map.put("address.street", "12 Long street");
     form.copyFrom(map);
  }
 
For more information on how Fields and Objects are copied see ContainerUtils.copyObjectToContainer(java.lang.Object, net.sf.click.control.Container).

Parameters:
object - the object to obtain attribute values from
Throws:
IllegalArgumentException - if the object parameter is null

copyFrom

public void copyFrom(Object object,
                     boolean debug)
Copy the given object's attributes into the Form's field values. In other words automatically populate Forms field values with the given objects attributes. copyFrom also supports java.util.Map as an argument.

If the debug parameter is true, debugging messages will be logged.

Parameters:
object - the object to obtain attribute values from
debug - log debug statements when populating the form
Throws:
IllegalArgumentException - if the object parameter is null
See Also:
copyFrom(java.lang.Object)

copyTo

public void copyTo(Object object)
Copy the Form's field values into the given object's attributes. In other words automatically populate Object attributes with the Form's field values.

The following example populates the Customer attributes with the Form's field values:

  public void onPost() {
      if (form.isValid()) {
         Customer customer = new Customer();
         form.copyTo(customer);
         ..
      }
      return true;
  }
 
copyTo also supports java.util.Map as an argument.

By specifying a map, the map's key/value pairs are populated from matching Form field names. A match occurs when a field's name is equal to a map's key.

The following example populates the map with the Form field values:

  public void onInit() {
     form = new Form("form");
     form.add(new TextField("name"));
     form.add(new TextField("address.street"));
  }

  public void onGet() {
     Map map = new HashMap();
     map.put("name", null);
     map.put("address.street", null);
     form.copyTo(map);
  }
 
Note that the map acts as a template to specify which fields to populate from. For more information on how Fields and Objects are copied see ContainerUtils.copyContainerToObject(net.sf.click.control.Container, java.lang.Object).

Parameters:
object - the object to populate with field values
Throws:
IllegalArgumentException - if the object parameter is null

copyTo

public void copyTo(Object object,
                   boolean debug)
Copy the Form's field values into the given object's attributes. In other words automatically populate Object attributes with the Forms field values. copyTo also supports java.util.Map as an argument.

If the debug parameter is true, debugging messages will be logged.

Parameters:
object - the object to populate with field values
debug - log debug statements when populating the object
Throws:
IllegalArgumentException - if the object parameter is null
See Also:
copyTo(java.lang.Object)

onProcess

public boolean onProcess()
Process the Form and its child controls only if the Form was submitted by the user.

This method invokes isFormSubmission() to check whether the form was submitted or not.

The Forms processing order is:

  1. All Field controls in the order they were added
  2. All Button controls in the order they were added
  3. Invoke the Forms listener if defined

Specified by:
onProcess in interface Control
Overrides:
onProcess in class AbstractContainer
Returns:
true to continue Page event processing or false otherwise
See Also:
Context.getRequestParameter(String), Context.getFileItemMap()

onDestroy

public void onDestroy()
Destroy the controls contained in the Form and clear any form error message.

Specified by:
onDestroy in interface Control
Overrides:
onDestroy in class AbstractContainer
See Also:
Control.onDestroy()

validate

public void validate()
Validate the Form request submission.

A form error message is displayed if a validation error occurs. These messages are defined in the resource bundle:

  • /click-control.properties
    • file-size-limit-exceeded-error
    • post-size-limit-exceeded-error


onSubmitCheck

public boolean onSubmitCheck(Page page,
                             String redirectPath)
Perform a form submission check ensuring the user has not replayed the form submission by using the browser back button. If the form submit is valid this method will return true, otherwise set the page to redirect to the given redirectPath and return false.

This method will add a token to the user's session and a hidden field to the form to validate future submits.

Form submit checks should be performed before the pages controls are processed in the Page onSecurityCheck method. For example:

 public class Order extends Page {
     ..

     public boolean onSecurityCheck() {
         return form.onSubmitCheck(this, "/invalid-submit.html");
     }
 } 
Form submit checks should generally be combined with the Post-Redirect pattern which provides a better user experience when pages are refreshed.

Please note: a call to onSubmitCheck always succeeds for Ajax requests.

Parameters:
page - the page invoking the Form submit check
redirectPath - the path to redirect invalid submissions to
Returns:
true if the form submit is OK or false otherwise
Throws:
IllegalArgumentException - if the page or redirectPath is null

onSubmitCheck

public boolean onSubmitCheck(Page page,
                             Class pageClass)
Perform a form submission check ensuring the user has not replayed the form submission by using the browser back button. If the form submit is valid this method will return true, otherwise set the page to redirect to the given Page class and return false.

This method will add a token to the user's session and a hidden field to the form to validate future submits.

Form submit checks should be performed before the pages controls are processed in the Page onSecurityCheck method. For example:

 public class Order extends Page {
     ..

     public boolean onSecurityCheck() {
         return form.onSubmitCheck(this, InvalidSubmitPage.class);
     }
 } 
Form submit checks should generally be combined with the Post-Redirect pattern which provides a better user experience when pages are refreshed.

Please note: a call to onSubmitCheck always succeeds for Ajax requests.

Parameters:
page - the page invoking the Form submit check
pageClass - the page class to redirect invalid submissions to
Returns:
true if the form submit is OK or false otherwise
Throws:
IllegalArgumentException - if the page or pageClass is null

onSubmitCheck

public boolean onSubmitCheck(Page page,
                             Object submitListener,
                             String submitListenerMethod)
Perform a form submission check ensuring the user has not replayed the form submission by using the browser back button. If the form submit is valid this method will return true, otherwise the given listener object and method will be invoked.

This method will add a token to the users session and a hidden field to the form to validate future submit's.

Form submit checks should be performed before the pages controls are processed in the Page onSecurityCheck method. For example:

 public class Order extends Page {
     ..

     public boolean onSecurityCheck() {
         return form.onSubmitCheck(this, this, "onInvalidSubmit");
     }

     public boolean onInvalidSubmit() {
        getContext().setRequestAttribute("invalidPath", getPath());
        setForward("invalid-submit.htm");
        return false;
     }
 } 
Form submit checks should generally be combined with the Post-Redirect pattern which provides a better user experience when pages are refreshed.

Please note: a call to onSubmitCheck always succeeds for Ajax requests.

Parameters:
page - the page invoking the Form submit check
submitListener - the listener object to call when an invalid submit occurs
submitListenerMethod - the listener method to invoke when an invalid submit occurs
Returns:
true if the form submit is valid, or the return value of the listener method otherwise
Throws:
IllegalArgumentException - if the page, submitListener or submitListenerMethod is null

startTag

public String startTag()
Return the rendered opening form tag and all the forms hidden fields.

Returns:
the rendered form start tag and the forms hidden fields

endTag

public String endTag()
Return the rendered form end tag and JavaScript for field focus and validation.

Returns:
the rendered form end tag

render

public void render(HtmlStringBuffer buffer)
Render the HTML representation of the Form.

If the form contains errors after processing, these errors will be rendered.

Specified by:
render in interface Control
Overrides:
render in class AbstractContainer
Parameters:
buffer - the specified buffer to render the control's output to
See Also:
AbstractContainer.toString()

performSubmitCheck

protected boolean performSubmitCheck()
Perform a back button submit check, returning true if the request is valid or false otherwise. This method will add a submit check token to the form as a hidden field, and to the session.

Returns:
true if the submit is OK or false otherwise

getFormSizeEst

protected int getFormSizeEst(List formFields)
Return the estimated rendered form size in characters.

Parameters:
formFields - the list of form fields
Returns:
the estimated rendered form size in characters

renderHeader

protected void renderHeader(HtmlStringBuffer buffer,
                            List formFields)
Render the given form start tag and the form hidden fields to the given buffer.

Parameters:
buffer - the HTML string buffer to render to
formFields - the list of form fields

renderFields

protected void renderFields(HtmlStringBuffer buffer)
Render the non hidden Form Fields to the string buffer.

This method delegates the rendering of the form fields to renderControls(HtmlStringBuffer, Container, List, Map, int).

Parameters:
buffer - the StringBuffer to render to

renderControls

protected void renderControls(HtmlStringBuffer buffer,
                              Container container,
                              List controls,
                              Map fieldWidths,
                              int columns)
Render the specified controls of the container to the string buffer.

fieldWidths is a map specifying the width for specific fields contained in the list of controls. The fieldWidths map is keyed on field name.

Parameters:
buffer - the StringBuffer to render to
container - the container which controls to render
controls - the controls to render
fieldWidths - a map of field widths keyed on field name
columns - the number of form layout table columns

renderErrors

protected void renderErrors(HtmlStringBuffer buffer,
                            boolean processed)
Render the form errors to the given buffer is form processed.

Parameters:
buffer - the string buffer to render the errors to
processed - the flag indicating whether has been processed

renderButtons

protected void renderButtons(HtmlStringBuffer buffer)
Render the given list of Buttons to the string buffer.

Parameters:
buffer - the StringBuffer to render to

renderTagEnd

protected void renderTagEnd(List formFields,
                            HtmlStringBuffer buffer)
Close the form tag and render any additional content after the Form.

Additional content includes javascript validation and javascript focus scripts.

Parameters:
formFields - all fields contained within the form
buffer - the buffer to render to

renderFocusJavaScript

protected void renderFocusJavaScript(HtmlStringBuffer buffer,
                                     List formFields)
Render the Form field focus JavaScript to the string buffer.

Parameters:
buffer - the StringBuffer to render to
formFields - the list of form fields

renderValidationJavaScript

protected void renderValidationJavaScript(HtmlStringBuffer buffer,
                                          List formFields)
Render the Form validation JavaScript to the string buffer.

Parameters:
buffer - the StringBuffer to render to
formFields - the list of form fields

hasPostError

protected boolean hasPostError()
Returns true if a POST error occurred, false otherwise.

Returns:
true if a POST error occurred, false otherwise