wicket.markup.html.form
Class Form

java.lang.Object
  extended by wicket.Component
      extended by wicket.MarkupContainer
          extended by wicket.markup.html.WebMarkupContainer
              extended by wicket.markup.html.form.Form
All Implemented Interfaces:
java.io.Serializable, IRequestListener, IFormSubmitListener

public class Form
extends WebMarkupContainer
implements IFormSubmitListener

Base class for forms. To implement a form, subclass this class, add FormComponents (such as CheckBoxes, ListChoices or TextFields) to the form. You can nest multiple buttons if you want to vary submit behavior. However, it is not necessary to use Wicket's button class, just putting e.g. <input type="submit" value="go"> suffices.

By default, the processing of a form works like this:

  • The submitting button is looked up. A submitting button is a button that is nested in this form (is a child component) and that was clicked by the user. If a submitting button was found, and it has the defaultFormProcessing field set to false (default is true), it's onSubmit method will be called right away, thus no validition is done, and things like updating form component models that would normally be done are skipped. In that respect, nesting a button with the defaultFormProcessing field set to false has the same effect as nesting a normal link. If you want you can call validate() to execute form validation, hasError() to find out whether validate() resulted in validation errors, and updateFormComponentModels() to update the models of nested form components.
  • When no submitting button with defaultFormProcessing set to false was found, this form is processed (method process()). Now, two possible paths exist:
  • Form for handling (file) uploads with multipart requests is supported by callign setMultiPart(true) ( although wicket will try to automatically detect this for you ). Use this with FileUploadField components. You can attach mutliple FileUploadField components for muliple file uploads.

    In case of an upload error two resource keys are available to specify error messages: uploadTooLarge and uploadFailed ie in [page].properties [form-id].uploadTooLarge=You have uploaded a file that is over the allowed limit of 2Mb

    If you want to have multiple buttons which submit the same form, simply put two or more button components somewhere in the hierarchy of components that are children of the form.

    To get form components to persist their values for users via cookies, simply call setPersistent(true) on the form component.

    Author:
    Jonathan Locke, Juergen Donnerstag, Eelco Hillenius, Cameron Braid, Johan Compagner, Igor Vaynberg (ivaynberg)
    See Also:
    Serialized Form

    Nested Class Summary
     
    Nested classes/interfaces inherited from class wicket.Component
    Component.ComponentModelChange, Component.EnabledChange, Component.IVisitor, Component.VisibilityChange
     
    Field Summary
     
    Fields inherited from class wicket.Component
    ENABLE, FLAG_RESERVED1, FLAG_RESERVED2, FLAG_RESERVED3, FLAG_RESERVED4, FLAG_RESERVED5, FLAG_RESERVED6, FLAG_RESERVED7, FLAG_RESERVED8, PATH_SEPARATOR, RENDER
     
    Fields inherited from interface wicket.markup.html.form.IFormSubmitListener
    INTERFACE
     
    Constructor Summary
    Form(java.lang.String id)
              Constructs a form with no validation.
    Form(java.lang.String id, IModel model)
               
     
    Method Summary
     void add(IFormValidator validator)
              Adds a form validator to the form.
    protected  void appendDefaultButtonField(MarkupStream markupStream, ComponentTag openTag)
              If a default button was set on this form, this method will be called to render an extra field with an invisible style so that pressing enter in one of the textfields will do a form submit using this button.
    protected  void beforeUpdateFormComponentModels()
              Template method to allow clients to do any processing (like recording the current model so that, in case onSubmit does further validation, the model can be rolled back) before the actual updating of form component models is done.
     void clearInput()
              Clears the input from the form's nested children of type FormComponent.
    protected  void delegateSubmit(Button submittingButton)
              Called (by the default implementation of 'process') when all fields validated, the form was updated and it's data was allowed to be persisted.
     void error(java.lang.String error, java.util.Map args)
              /** Registers an error feedback message for this component
     Button findSubmittingButton()
              Gets the button which submitted this form.
     Button getDefaultButton()
              Gets the default button.
    protected  java.lang.String getHiddenFieldId()
              Returns the HiddenFieldId which will be used as the name and id property of the hiddenfield that is generated for event dispatches.
    protected  java.lang.String getJavascriptId()
              Returns the javascript/css id of this form that will be used to generated the id="xxx" attribute.
     java.lang.CharSequence getJsForInterfaceUrl(java.lang.CharSequence url)
              This generates a piece of javascript code that sets the url in the special hidden field and submits the form.
     Bytes getMaxSize()
               
     java.lang.String getValidatorKeyPrefix()
              Returns the prefix used when building validator keys.
    protected  IValuePersister getValuePersister()
              Gets the form component persistence manager; it is lazy loaded.
     boolean hasError()
              Gets whether the current form has any error registered.
    protected  void internalOnDetach()
              THIS METHOD IS NOT PART OF THE WICKET PUBLIC API.
    protected  void internalOnModelChanged()
              THIS METHOD IS NOT PART OF THE WICKET PUBLIC API.
     boolean isSubmitted()
              Checks if this form has been submitted during the current request
     boolean isVersioned()
              Method made final because we want to ensure users call setVersioned.
     void loadPersistentFormComponentValues()
              THIS METHOD IS NOT PART OF THE WICKET PUBLIC API.
    protected  void markFormComponentsInvalid()
              Mark each form component on this form invalid.
    protected  void markFormComponentsValid()
              Mark each form component on this form valid.
    protected  void onComponentTag(ComponentTag tag)
              Processes the component tag.
    protected  void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag)
              Append an additional hidden input tag to support anchor tags that can submit a form.
    protected  void onError()
              Method to override if you want to do something special when an error occurs (other than simply displaying validation errors).
     void onFormSubmitted()
              THIS METHOD IS NOT PART OF THE WICKET API.
    protected  void onRender(MarkupStream markupStream)
              Renders this component.
    protected  void onSubmit()
              Implemented by subclasses to deal with form submits.
     boolean process()
              Process the form.
     void removePersistentFormComponentValues(boolean disablePersistence)
              Removes already persisted data for all FormComponent childs and disable persistence for the same components.
     void setDefaultButton(Button button)
              Sets the default button.
     void setMaxSize(Bytes maxSize)
               
     void setMultiPart(boolean multiPart)
              Set to true to use enctype='multipart/form-data', and to process file uplloads by default multiPart = false
     Component setVersioned(boolean isVersioned)
               
    protected  void updateFormComponentModels()
              Update the model of all form components using the fields that were sent with the current request.
    protected  void validate()
              Validates the form.
    protected  void validateFormValidator(IFormValidator validator)
              Validates form with the given form validator
     void visitFormComponents(FormComponent.IVisitor visitor)
              Convenient and typesafe way to visit all the form components on a form
     
    Methods inherited from class wicket.markup.html.WebMarkupContainer
    getMarkupType, getWebPage
     
    Methods inherited from class wicket.MarkupContainer
    add, autoAdd, contains, findMarkupStream, get, getAssociatedMarkupStream, getMarkupStream, internalAdd, internalAttach, internalDetach, isTransparentResolver, iterator, iterator, newMarkupResourceStream, remove, remove, removeAll, renderAll, renderAssociatedMarkup, renderComponentTagBody, replace, setMarkupStream, setModel, size, toString, toString, visitChildren, visitChildren
     
    Methods inherited from class wicket.Component
    add, addStateChange, checkComponentTag, checkComponentTagAttribute, continueToOriginalDestination, debug, detachBehaviors, detachModel, detachModels, error, exceptionMessage, fatal, findPage, findParent, findParentWithAssociatedMarkup, getApplication, getApplicationPages, getApplicationSettings, getBehaviors, getBehaviors, getClassRelativePath, getConverter, getEscapeModelStrings, getFeedbackMessage, getFlag, getFlag, getId, getLocale, getLocalizer, getMarkupAttributes, getMarkupId, getMetaData, getModel, getModelComparator, getModelObject, getModelObjectAsString, getOutputMarkupId, getPage, getPageFactory, getPageRelativePath, getParent, getPath, getRenderBodyOnly, getRequest, getRequestCycle, getResponse, getSession, getSizeInBytes, getString, getString, getString, getStyle, getVariation, hasErrorMessage, hasFeedbackMessage, info, initModel, internalOnAttach, isActionAuthorized, isAncestorOf, isBehaviorAccepted, isEnableAllowed, isEnabled, isHeadRendered, isIgnoreAttributeModifier, isRenderAllowed, isVisible, isVisibleInHierarchy, modelChanged, modelChanging, newPage, newPage, onAfterRender, onAttach, onBeforeRender, onBeginRequest, onDetach, onEndRequest, onModelChanged, onModelChanging, onRender, redirectToInterceptPage, remove, render, render, renderComponent, renderComponent, renderComponentTag, rendered, renderedBehaviors, renderHead, replaceComponentTagBody, replaceWith, resetHeadRendered, sameRootModel, sameRootModel, setAuto, setEnabled, setEscapeModelStrings, setFlag, setFlag, setIgnoreAttributeModifier, setMetaData, setModelObject, setOutputMarkupId, setRedirect, setRenderBodyOnly, setResponsePage, setResponsePage, setResponsePage, setVisible, urlFor, urlFor, urlFor, urlFor, urlFor, visitParents, warn
     
    Methods inherited from class java.lang.Object
    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
     

    Constructor Detail

    Form

    public Form(java.lang.String id)
    Constructs a form with no validation.

    Parameters:
    id - See Component

    Form

    public Form(java.lang.String id,
                IModel model)
    Parameters:
    id - See Component
    model - See Component
    See Also:
    Component.Component(String, IModel)
    Method Detail

    getDefaultButton

    public final Button getDefaultButton()
    Gets the default button. If set (not null), a hidden submit button will be rendered right after the form tag, so that when users press enter in a textfield, this button's action will be selected. If no default button is set (it is null), nothing additional is rendered.

    WARNING: note that this is a best effort only. Unfortunately having a 'default' button in a form is ill defined in the standards, and of course IE has it's own way of doing things.

    Returns:
    The button to set as the default button, or null when you want to 'unset' any previously set default button

    getMaxSize

    public Bytes getMaxSize()
    Returns:
    the maxSize of uploaded files

    loadPersistentFormComponentValues

    public final void loadPersistentFormComponentValues()
    THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL IT.

    Retrieves FormComponent values related to the page using the persister and assign the values to the FormComponent. Thus initializing them.


    onFormSubmitted

    public final void onFormSubmitted()
    THIS METHOD IS NOT PART OF THE WICKET API. DO NOT ATTEMPT TO OVERRIDE OR CALL IT. Handles form submissions.

    Specified by:
    onFormSubmitted in interface IFormSubmitListener
    See Also:
    validate()

    isSubmitted

    public final boolean isSubmitted()
    Checks if this form has been submitted during the current request

    Returns:
    true if the form has been submitted during this request, false otherwise

    internalOnDetach

    protected void internalOnDetach()
    Description copied from class: Component
    THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR OVERRIDE. Called when a request ends.

    Overrides:
    internalOnDetach in class Component
    See Also:
    Component.internalOnDetach()

    removePersistentFormComponentValues

    public void removePersistentFormComponentValues(boolean disablePersistence)
    Removes already persisted data for all FormComponent childs and disable persistence for the same components.

    Parameters:
    disablePersistence - if true, disable persistence for all FormComponents on that page. If false, it will remain unchanged.
    See Also:
    Page.removePersistedFormData(Class, boolean)

    setDefaultButton

    public final void setDefaultButton(Button button)
    Sets the default button. If set (not null), a hidden submit button will be rendered right after the form tag, so that when users press enter in a textfield, this button's action will be selected. If no default button is set (so unset by calling this method with null), nothing additional is rendered.

    WARNING: note that this is a best effort only. Unfortunately having a 'default' button in a form is ill defined in the standards, and of course IE has it's own way of doing things.

    Parameters:
    button - The button to set as the default button, or null when you want to 'unset' any previously set default button

    setMaxSize

    public void setMaxSize(Bytes maxSize)
    Parameters:
    maxSize - The maxSize for uploaded files

    setMultiPart

    public void setMultiPart(boolean multiPart)
    Set to true to use enctype='multipart/form-data', and to process file uplloads by default multiPart = false

    Parameters:
    multiPart - whether this form should behave as a multipart form

    setVersioned

    public final Component setVersioned(boolean isVersioned)
    Overrides:
    setVersioned in class Component
    Parameters:
    isVersioned - True to turn on versioning for this component, false to turn it off for this component and any children.
    Returns:
    This
    See Also:
    Component.setVersioned(boolean)

    isVersioned

    public boolean isVersioned()
    Method made final because we want to ensure users call setVersioned.

    Overrides:
    isVersioned in class Component
    Returns:
    True if this component is versioned
    See Also:
    Component.isVersioned()

    visitFormComponents

    public final void visitFormComponents(FormComponent.IVisitor visitor)
    Convenient and typesafe way to visit all the form components on a form

    Parameters:
    visitor - The visitor interface to call

    appendDefaultButtonField

    protected void appendDefaultButtonField(MarkupStream markupStream,
                                            ComponentTag openTag)
    If a default button was set on this form, this method will be called to render an extra field with an invisible style so that pressing enter in one of the textfields will do a form submit using this button. This method is overridable as what we do is best effort only, and may not what you want in specific situations. So if you have specific usability concerns, or want to follow another strategy, you may override this method.

    Parameters:
    markupStream - The markup stream
    openTag - The open tag for the body

    beforeUpdateFormComponentModels

    protected void beforeUpdateFormComponentModels()
    Template method to allow clients to do any processing (like recording the current model so that, in case onSubmit does further validation, the model can be rolled back) before the actual updating of form component models is done.


    delegateSubmit

    protected void delegateSubmit(Button submittingButton)
    Called (by the default implementation of 'process') when all fields validated, the form was updated and it's data was allowed to be persisted. It is meant for delegating further processing to clients.

    This implementation first finds out whether the form processing was triggered by a nested button of this form. If that is the case, that button's onSubmit is called first.

    Regardless of whether a submitting button was found, the form's onSubmit method is called next.

    Parameters:
    submittingButton - the button that triggered this form processing, or null if the processing was triggered by something else (like a non-Wicket submit button or a javascript execution)

    findSubmittingButton

    public final Button findSubmittingButton()
    Gets the button which submitted this form.

    Returns:
    The button which submitted this form or null if the processing was not trigger by a registered button component

    getValuePersister

    protected IValuePersister getValuePersister()
    Gets the form component persistence manager; it is lazy loaded.

    Returns:
    The form component value persister

    hasError

    public final boolean hasError()
    Gets whether the current form has any error registered.

    Returns:
    True if this form has at least one error.

    internalOnModelChanged

    protected void internalOnModelChanged()
    Description copied from class: Component
    THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR OVERRIDE. Called anytime a model is changed via setModel or setModelObject.

    Overrides:
    internalOnModelChanged in class Component
    See Also:
    Component.internalOnModelChanged()

    markFormComponentsInvalid

    protected final void markFormComponentsInvalid()
    Mark each form component on this form invalid.


    markFormComponentsValid

    protected final void markFormComponentsValid()
    Mark each form component on this form valid.


    getHiddenFieldId

    protected final java.lang.String getHiddenFieldId()
    Returns the HiddenFieldId which will be used as the name and id property of the hiddenfield that is generated for event dispatches.

    Returns:
    The name and id of the hidden field.

    getJavascriptId

    protected final java.lang.String getJavascriptId()
    Returns the javascript/css id of this form that will be used to generated the id="xxx" attribute. it will be generated if not set already in the onComponentTag. Where it will be tried to load from the markup first before it is generated.

    Returns:
    The javascript/css id of this form.

    onComponentTagBody

    protected void onComponentTagBody(MarkupStream markupStream,
                                      ComponentTag openTag)
    Append an additional hidden input tag to support anchor tags that can submit a form.

    Overrides:
    onComponentTagBody in class MarkupContainer
    Parameters:
    markupStream - The markup stream
    openTag - The open tag for the body

    onComponentTag

    protected void onComponentTag(ComponentTag tag)
    Description copied from class: Component
    Processes the component tag.

    Overrides:
    onComponentTag in class Component
    Parameters:
    tag - Tag to modify
    See Also:
    Component.onComponentTag(ComponentTag)

    onError

    protected void onError()
    Method to override if you want to do something special when an error occurs (other than simply displaying validation errors).


    onRender

    protected void onRender(MarkupStream markupStream)
    Description copied from class: MarkupContainer
    Renders this component. This implementation just calls renderComponent.

    Overrides:
    onRender in class MarkupContainer
    See Also:
    Component.onRender(MarkupStream)

    onSubmit

    protected void onSubmit()
    Implemented by subclasses to deal with form submits.


    process

    public boolean process()
    Process the form. Though you can override this method to provide your whole own algorithm, it is not recommended to do so.

    See the class documentation for further details on the form processing

    Returns:
    False if the form had an error

    updateFormComponentModels

    protected final void updateFormComponentModels()
    Update the model of all form components using the fields that were sent with the current request.

    See Also:
    FormComponent.updateModel()

    clearInput

    public final void clearInput()
    Clears the input from the form's nested children of type FormComponent. This method is typically called when a form needs to be reset.


    validate

    protected void validate()
    Validates the form. This method is typically called before updating any models.


    validateFormValidator

    protected final void validateFormValidator(IFormValidator validator)
    Validates form with the given form validator

    Parameters:
    validator -

    getJsForInterfaceUrl

    public final java.lang.CharSequence getJsForInterfaceUrl(java.lang.CharSequence url)
    This generates a piece of javascript code that sets the url in the special hidden field and submits the form. Warning: This code should only be called in the rendering phase for form components inside the form because it uses the css/javascript id of the form which can be stored in the markup.

    Parameters:
    url - The interface url that has to be stored in the hidden field and submitted
    Returns:
    The javascript code that submits the form.

    getValidatorKeyPrefix

    public java.lang.String getValidatorKeyPrefix()
    Returns the prefix used when building validator keys. This allows a form to use a separate "set" of keys. For example if prefix "short" is returned, validator key short.RequiredValidator will be tried instead of RequiredValidator key.

    This can be useful when different designs are used for a form. In a form where error messages are displayed next to their respective form components as opposed to at the top of the form, the ${label} attribute is of little use and only causes redundant information to appear in the message. Forms like these can return the "short" (or any other string) validator prefix and declare key: short.RequiredValidator=required to override the longer message which is usually declared like this: RequiredValidator=${label} is a required field

    Returned prefix will be used for all form components. The prefix can also be overridden on form component level by overriding FormComponent.getValidatorKeyPrefix()

    Returns:
    prefix prepended to validator keys

    add

    public void add(IFormValidator validator)
    Adds a form validator to the form.

    Parameters:
    validator - validator
    See Also:
    IFormValidator

    error

    public final void error(java.lang.String error,
                            java.util.Map args)
    /** Registers an error feedback message for this component

    Parameters:
    error - error message
    args - argument replacement map for ${key} variables


    Copyright © 2004-2007 Wicket developers. All Rights Reserved.