Class Form

  • All Implemented Interfaces:
    Serializable, org.apache.click.Stateful, org.openidentityplatform.openam.click.Control, Container

    public class Form
    extends AbstractContainer
    implements org.apache.click.Stateful
    Provides a Form control:   <form method='post'>.
    Example
    Example
    <label>Username</label>* <input type='text' name='username' value='' size='20' maxlength='20'>
    <label>Password</label>* <input type='password' name='password' value='' size='20' maxlength='20'>
    Example
    <input type='submit' name='ok' value=' OK '> <input type='submit' name='cancel' value=' Cancel '>
    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 also provides a validate() method where subclasses can provide custom cross-field validation.

    File Upload Validation

    The Form's validateFileUpload() provides validation for multipart requests (multipart requests are used for uploading files from the browser). The validateFileUpload() method checks that files being uploaded do not exceed the maximum request size or the maximum file size.

    Note: if the maximum request size or maximum file size is exceeded, the request is deemed invalid (hasPostError will return true), 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 validateFileUpload() 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 resources

    The Form control makes use of the following resources (which Click automatically deploys to the application directory, /click):
    • click/control.css
    • click/control.js
    To import these files and any form control imports simply reference the variables $headElements and $jsElements in the page template. For example:
     <html>
     <head>
     $headElements
     </head>
     <body>
    
     $form
    
     $jsElements
     </body>
     </html> 

    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:
    Example
    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:
    • method - the form submission method ["post" | "get"]
    • name - the name of your form, important when using JavaScript
    • action - directs the Page where the form should be submitted to
    • form_name - include a hidden field which specifies the AbstractControl.name of the Form
    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 laid 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:
    • Put your macros if a file called macro.vm in your applications root directory.
    • Put your macros in the auto deployed click/VM_global_macro.vm file.
    • Create a custom named macro file and reference it in a WEB-INF/velocity.properties file under the property named velocimacro.library.

    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(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.

    Dynamic Forms and not validating a request

    A common use case for web applications is to create Form fields dynamically based upon user selection. For example if a checkbox is ticked another Field is added to the Form. A simple way to achieve this is using JavaScript to submit the Form when the Field is changed or clicked.

    When submitting a Form using JavaScript, it is often desirable to not validate the fields since the user is still filling out the form. To cater for this use case, Form provides the setValidate(boolean) to switch off form and field validation. For example:

     public void onInit() {
         checkbox.setAttribute("onclick", "form.submit()");
    
         // Since onInit occurs before the onProcess event,
         // we have to explicitly bind the submit button in the onInit event if we
         // want to check if it was clicked.
         // If the submit button wasn't clicked it means the Form was submitted
         // using JavaScript and we don't want to validate yet
         ClickUtils.bind(submit);
    
         // If submit was not clicked, don't validate
         if(form.isFormSubmission() && !submit.isClicked()) {
             form.setValidate(false);
         }
     } 

     

    See also the W3C HTML reference: FORM

    See Also:
    Field, Submit, Serialized Form
    • Field Detail

      • 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
      • 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
      • FOCUS_JAVASCRIPT

        protected static final String FOCUS_JAVASCRIPT
        The Form set field focus JavaScript.
        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<Field> 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<Button> 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<String,​Integer> fieldWidths
        The map of field width values.
      • formSubmission

        protected Boolean formSubmission
        Flag indicating whether this form was submitted.
      • 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

      • insert

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

        Please note: if the form contains a control with the same name as the given control, that control will be replaced by the given control. If a control has no name defined it cannot be replaced.

        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.

        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 if the Field name is not defined
        IndexOutOfBoundsException - if index is out of range (index < 0 || index > getControls().size())
        See Also:
        Container.insert(Control, int)
      • add

        public org.openidentityplatform.openam.click.Control add​(org.openidentityplatform.openam.click.Control control)
        Add a Control to the form and return the added instance.

        Please note: if the form contains a control with the same name as the given control, that control will be replaced by the given control. If a control has no name defined it cannot be replaced.

        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(Control)
      • add

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

        Please note: if the form contains a control with the same name as the given control, that control will be replaced by the given control. If a control has no name defined it cannot be replaced.

        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(Control)
      • add

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

        Please note: if the form contains a control with the same name as the given control, that control will be replaced by the given control. If a control has no name defined it cannot be replaced.

        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(Control)
      • add

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

        Please note: if the form contains a control with the same name as the given control, that control will be replaced by the given control. If a control has no name defined it cannot be replaced.

        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(Control)
      • replace

        public org.openidentityplatform.openam.click.Control replace​(org.openidentityplatform.openam.click.Control currentControl,
                                                                     org.openidentityplatform.openam.click.Control newControl)
        Deprecated.
        this method was used for stateful pages, which have been deprecated
        Replace the control in the form at the specified index, and return the newly added control.
        Specified by:
        replace in interface Container
        Overrides:
        replace in class AbstractContainer
        Parameters:
        currentControl - the control currently contained in the form
        newControl - the control to replace the current control contained in the form
        Returns:
        the new control that replaced the current control
        Throws:
        IllegalArgumentException - if the currentControl or newControl is null
        IllegalStateException - if the currentControl is not contained in the form
        See Also:
        Container.replace(Control, Control)
      • remove

        public boolean remove​(org.openidentityplatform.openam.click.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(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<String> 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
      • 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<Field> 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
      • getHeadElements

        public List<Element> getHeadElements()
        Return the Form HEAD elements to be included in the page. The following resources are returned:
        • click/control.css
        • click/control.js
        Specified by:
        getHeadElements in interface org.openidentityplatform.openam.click.Control
        Overrides:
        getHeadElements in class AbstractControl
        Returns:
        the form list of HEAD elements to be included in the page
        See Also:
        Control.getHeadElements()
      • 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:

        • the Form name must be present as a request parameter (Form automatically adds a HiddenField which value is set to the Form name. This ensures the Form name is present when submitting the form)
        • the request method must equal the Form method, for example both must be GET or POST
        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 org.openidentityplatform.openam.click.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<Field> 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<String,​org.openidentityplatform.openam.click.Control> 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<Button> 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
      • getFieldWidths

        public Map<String,​Integer> getFieldWidths()
        Return the map of field width values, keyed on field name.
        Returns:
        the map of field width values, keyed on field name
      • isJavaScriptValidation

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

        public boolean getJavaScriptValidation()
        Deprecated.
        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.

        This value can be overridden by Fields through their Field.setParentStyleHint(String) property.

        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 org.openidentityplatform.openam.click.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(Object,org.openidentityplatform.openam.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(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(org.openidentityplatform.openam.click.control.Container, 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(Object)
      • getState

        public Object getState()
        Return the form state. The following state is returned:
        • all the input Field values and FieldSets contained in the Form and child containers.
        Specified by:
        getState in interface org.apache.click.Stateful
        Returns:
        the state of input Fields and FieldSets contained in the form
      • setState

        public void setState​(Object state)
        Set the Form state. The state will be applied to all the input Fields and FieldSets contained in the Form or child containers.
        Specified by:
        setState in interface org.apache.click.Stateful
        Parameters:
        state - the Form state to set
      • 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
        This method delegates validation to validate() while file upload validation are delegated to validateFileUpload().
        Specified by:
        onProcess in interface org.openidentityplatform.openam.click.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 org.openidentityplatform.openam.click.Control
        Overrides:
        onDestroy in class AbstractContainer
        See Also:
        Control.onDestroy()
      • validate

        public void validate()
        The validate method is invoked by onProcess() to validate the request submission. A Form subclass can override this method to implement cross-field validation logic.

        If the Form determines that the submission is invalid it should set the error property with an appropriate error message. For example:

         public class RegistrationForm extends Form {
        
             // Add validation to ensure the password and confirmPassword fields match
             public void validate() {
                 String password = getFieldValue("password");
                 String confirmPassword = getFieldValue("confirmPassword");
                 if (!password.equals(confirmPassword)) {
        
                     // Set Form's error property value that will be shown to the user
                     setError("The passwords do not match.");
                 }
             }
         } 
      • onSubmitCheck

        public boolean onSubmitCheck​(org.openidentityplatform.openam.click.Page page,
                                     String redirectPath)
        Perform a form submission check ensuring the user has not replayed the form submission by using the browser's back or refresh buttons or by clicking the Form submit button twice, in quick succession. 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​(org.openidentityplatform.openam.click.Page page,
                                     Class<? extends org.openidentityplatform.openam.click.Page> 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​(org.openidentityplatform.openam.click.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(his, 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
      • removeState

        public void removeState​(org.openidentityplatform.openam.click.Context context)
        Remove the Form state from the session for the given request context.
        Parameters:
        context - the request context
        See Also:
        saveState(Context), restoreState(Context)
      • restoreState

        public void restoreState​(org.openidentityplatform.openam.click.Context context)
        Restore the Form state from the session for the given request context.

        This method delegates to setState(Object) to set the form restored state.

        Parameters:
        context - the request context
        See Also:
        saveState(Context), removeState(Context)
      • saveState

        public void saveState​(org.openidentityplatform.openam.click.Context context)
        Save the Form state to the session for the given request context.

        * This method delegates to getState() to retrieve the form state to save.

        Parameters:
        context - the request context
        See Also:
        restoreState(Context), removeState(Context)
      • 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 org.openidentityplatform.openam.click.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<Field> 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<Field> 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
      • renderControls

        protected void renderControls​(HtmlStringBuffer buffer,
                                      Container container,
                                      List<org.openidentityplatform.openam.click.Control> controls,
                                      Map<String,​Integer> 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<Field> 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<Field> 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<Field> 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
      • validateFileUpload

        protected void validateFileUpload()
        Validate the request for any file upload (multipart) errors.

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

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