org.apache.wicket.markup.html.form
Class FormComponent

java.lang.Object
  extended by org.apache.wicket.Component
      extended by org.apache.wicket.MarkupContainer
          extended by org.apache.wicket.markup.html.WebMarkupContainer
              extended by org.apache.wicket.markup.html.form.LabeledWebMarkupContainer
                  extended by org.apache.wicket.markup.html.form.FormComponent
All Implemented Interfaces:
java.io.Serializable, IClusterable, IConverterLocator, IFormVisitorParticipant, ILabelProvider
Direct Known Subclasses:
AbstractOptions, AbstractSingleSelectChoice, AbstractTextComponent, Button, CheckBox, CheckGroup, FileUploadField, FormComponentPanel, ListMultipleChoice, RadioGroup, Select

public abstract class FormComponent
extends LabeledWebMarkupContainer
implements IFormVisitorParticipant

An HTML form component knows how to validate itself. Validators that implement IValidator can be added to the component. They will be evaluated in the order they were added and the first Validator that returns an error message determines the error message returned by the component.

FormComponents are not versioned by default. If you need versioning for your FormComponents, you will need to call Form.setVersioned(true), which will set versioning on for the form and all form component children.

If this component is required and that fails, the error key that is used is the "Required"; if the type conversion fails, it will use the key "IConverter" if the conversion failed in a converter, or "ConversionError" if type was explicitly specified via setType(Class) or a IPropertyReflectionAwareModel was used. Notice that both "IConverter" and "ConversionError" have a more specific variant of "key.classname" where classname is the type that we failed to convert to. Classname is not full qualified, so only the actual name of the class is used. Property expressions that can be used in error messages are:

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

Nested Class Summary
static class FormComponent.AbstractVisitor
          Visitor for traversing form components
static interface FormComponent.IVisitor
          Typesafe interface to code that is called when visiting a form component.
 
Nested classes/interfaces inherited from class org.apache.wicket.Component
Component.ComponentModelChange, Component.EnabledChange, Component.VisibilityChange
 
Field Summary
protected static short FLAG_CONVERT_EMPTY_INPUT_STRING_TO_NULL
          Make empty strings null values boolean.
static java.lang.String VALUE_SEPARATOR
          The value separator
 
Fields inherited from class org.apache.wicket.Component
ENABLE, FLAG_RESERVED1, FLAG_RESERVED2, FLAG_RESERVED3, FLAG_RESERVED4, FLAG_RESERVED5, FLAG_RESERVED6, FLAG_RESERVED7, FLAG_RESERVED8, PATH_SEPARATOR, RENDER
 
Constructor Summary
FormComponent(java.lang.String id)
           
FormComponent(java.lang.String id, IModel model)
           
 
Method Summary
 FormComponent add(IValidator validator)
          Adds a validator to this form component.
 boolean checkRequired()
          Checks if the form component's 'required' requirement is met by first checking isRequired() to see if it has to check for requirement.
 void clearInput()
          Clears the user input.
protected  void convertInput()
          Converts and validates the conversion of the raw input string into the object specified by getType() and records any errors.
protected  java.lang.Object convertValue(java.lang.String[] value)
          Subclasses should overwrite this if the conversion is not done through the type field and the IConverter.
 void error(IValidationError error)
          Reports a validation error against this form component.
protected  java.util.List getBehaviors(java.lang.Class type)
          Gets the subset of the currently coupled IBehaviors that are of the provided type as a unmodifiable list or null if there are no behaviors attached.
 java.lang.Object getConvertedInput()
          Gets the converted input.
 Form getForm()
           
 java.lang.String getInput()
          Gets the request parameter for this component as a string.
 java.lang.String[] getInputAsArray()
          Gets the request parameters for this component as strings.
 java.lang.String getInputName()
          Gets the string to be used for the name attribute of the form element.
protected  java.lang.String getModelValue()
           
 java.lang.String getRawInput()
          Use hasRawInput() to check if this component has raw input because null can mean 2 things: It doesn't have rawinput or the rawinput is really null.
 java.lang.Class getType()
           
 java.lang.String getValidatorKeyPrefix()
           
 java.util.List getValidators()
          Gets an unmodifiable list of validators for this FormComponent.
 java.lang.String getValue()
          Gets current value for a form component, which can be either input data entered by the user, or the component's model object if no input was provided.
 boolean hasRawInput()
          Returns whether this component has raw input.
protected  int inputAsInt()
          Gets the request parameter for this component as an int.
protected  int inputAsInt(int defaultValue)
          Gets the request parameter for this component as an int, using the given default in case no corresponding request parameter was found.
protected  int[] inputAsIntArray()
          Gets the request parameters for this component as ints.
 void inputChanged()
          Used by Form to tell the FormComponent that a new user input is available
protected  void internalOnModelChanged()
          THIS METHOD IS NOT PART OF THE WICKET PUBLIC API.
 void invalid()
          Indicate that validation of this form component failed.
 boolean isInputNullable()
          Gets whether this component's input can be null.
 boolean isMultiPart()
           
 boolean isPersistent()
           
 boolean isRequired()
           
 boolean isValid()
          Gets whether this component is 'valid'.
protected  void onComponentTag(ComponentTag tag)
          Processes the component tag.
protected  void onDetach()
          Sets the temporary converted input value to null.
protected  void onDisabled(ComponentTag tag)
          Called by onComponentTag(ComponentTag) when the component is disabled.
protected  void onInvalid()
          Handle invalidation
protected  void onValid()
          Handle validation
 boolean processChildren()
          Should children be traversed during visiting or should only the siblings be processed.
 void processInput()
          This method will retrieve the request parameter, validate it, and if valid update the model.
 void setConvertedInput(java.lang.Object convertedInput)
          Sets the converted input.
 FormComponent setLabel(IModel labelModel)
          The value will be made available to the validator property by means of ${label}.
 void setModelValue(java.lang.String value)
          Deprecated. call or override setModelValue(String[])
 void setModelValue(java.lang.String[] value)
          Sets the value for a form component.
 FormComponent setPersistent(boolean persistent)
          Sets whether this component is to be persisted.
 FormComponent setRequired(boolean required)
          Sets the required flag
 FormComponent setType(java.lang.Class type)
          Sets the type that will be used when updating the model for this component.
protected  boolean shouldTrimInput()
          Determines whether or not this component should trim its input prior to processing it.
protected  boolean supportsPersistence()
           
protected  java.lang.String trim(java.lang.String string)
          Trims the input according to shouldTrimInput()
 void updateModel()
          Updates this components model from the request, it expects that the object is already converted through the convertInput() call that is called by the validate() method when a form is being processed.
 void valid()
          Called to indicate that the user input is valid.
 void validate()
          Performs full validation of the form component, which consists of calling validateRequired(), convertInput(), and validateValidators().
protected  void validateRequired()
          Checks if the raw input value is not null if this component is required.
protected  void validateValidators()
          Validates this component using the component's validators.
static void visitFormComponentsPostOrder(Component component, FormComponent.IVisitor visitor)
          Visits any form components inside component if it is a container, or component itself if it is itself a form component
 
Methods inherited from class org.apache.wicket.markup.html.form.LabeledWebMarkupContainer
getLabel, setLabelInternal
 
Methods inherited from class org.apache.wicket.markup.html.WebMarkupContainer
getMarkupType, getWebPage
 
Methods inherited from class org.apache.wicket.MarkupContainer
add, addOrReplace, autoAdd, autoAdd, contains, findMarkupStream, get, getAssociatedMarkupStream, getMarkupStream, hasAssociatedMarkup, internalAdd, isTransparentResolver, iterator, iterator, newMarkupResourceStream, onComponentTagBody, onRender, remove, remove, removeAll, renderAll, renderAssociatedMarkup, renderComponentTagBody, replace, setMarkupStream, setModel, size, toString, toString, visitChildren, visitChildren
 
Methods inherited from class org.apache.wicket.Component
add, addStateChange, afterRender, beforeRender, callOnBeforeRenderIfNotVisible, checkComponentTag, checkComponentTagAttribute, checkHierarchyChange, continueToOriginalDestination, debug, detach, detachBehaviors, detachModel, detachModels, determineVisibility, error, exceptionMessage, fatal, findPage, findParent, findParentWithAssociatedMarkup, getApplication, getBehaviors, getBehaviorsRawList, getClassRelativePath, getComponentBorder, getConverter, getConverter, getEscapeModelStrings, getFeedbackMessage, getFlag, getFlag, getId, getInnermostModel, getInnermostModel, getLocale, getLocalizer, getMarkupAttributes, getMarkupId, getMarkupId, getMetaData, getModel, getModelComparator, getModelObject, getModelObjectAsString, getModelObjectAsString, getOutputMarkupId, getOutputMarkupPlaceholderTag, getPage, getPageFactory, getPageRelativePath, getParent, getPath, getRenderBodyOnly, getRequest, getRequestCycle, getResponse, getSession, getSizeInBytes, getStatelessHint, getString, getString, getString, getStyle, getVariation, hasBeenRendered, hasErrorMessage, hasFeedbackMessage, info, initModel, internalAttach, internalDetach, internalOnAttach, internalOnDetach, isActionAuthorized, isAncestorOf, isAttached, isBehaviorAccepted, isEnableAllowed, isEnabled, isIgnoreAttributeModifier, isRenderAllowed, isStateless, isVersioned, isVisibilityAllowed, isVisible, isVisibleInHierarchy, locateMarkupStream, markAttached, markRendering, modelChanged, modelChanging, newPage, newPage, onAfterRender, onAttach, onBeforeRender, onBeginRequest, onEndRequest, onModelChanged, onModelChanging, prepareForRender, redirectToInterceptPage, remove, remove, render, render, renderComponent, renderComponent, renderComponentTag, rendered, renderHead, replaceComponentTagBody, replaceWith, sameInnermostModel, sameInnermostModel, setAuto, setComponentBorder, setEnabled, setEscapeModelStrings, setFlag, setFlag, setIgnoreAttributeModifier, setMarkupId, setMetaData, setModelObject, setOutputMarkupId, setOutputMarkupPlaceholderTag, setRedirect, setRenderBodyOnly, setResponsePage, setResponsePage, setResponsePage, setVersioned, setVisibilityAllowed, setVisible, urlFor, urlFor, urlFor, urlFor, urlFor, urlFor, visitParents, warn, wrap
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

VALUE_SEPARATOR

public static java.lang.String VALUE_SEPARATOR
The value separator


FLAG_CONVERT_EMPTY_INPUT_STRING_TO_NULL

protected static final short FLAG_CONVERT_EMPTY_INPUT_STRING_TO_NULL
Make empty strings null values boolean. Used by AbstractTextComponent subclass.

See Also:
Constant Field Values
Constructor Detail

FormComponent

public FormComponent(java.lang.String id)
See Also:
Component.Component(String)

FormComponent

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

visitFormComponentsPostOrder

public static final void visitFormComponentsPostOrder(Component component,
                                                      FormComponent.IVisitor visitor)
Visits any form components inside component if it is a container, or component itself if it is itself a form component

Parameters:
component - starting point of the traversal
visitor - The visitor to call

add

public final FormComponent add(IValidator validator)
Adds a validator to this form component.

Parameters:
validator - The validator
Returns:
This
Throws:
java.lang.IllegalArgumentException - if validator is null
See Also:
IValidator, IValidatorAddListener

checkRequired

public boolean checkRequired()
Checks if the form component's 'required' requirement is met by first checking isRequired() to see if it has to check for requirement. If that is true then by default it checks if the input is null or an empty String Strings.isEmpty(CharSequence)

Subclasses that overwrite this method should also call isRequired() first.

Returns:
true if the 'required' requirement is met, false otherwise
See Also:
Strings.isEmpty(CharSequence), isInputNullable()

clearInput

public final void clearInput()
Clears the user input.


error

public void error(IValidationError error)
Reports a validation error against this form component. The actual error is reported by creating a ValidationErrorFeedback object that holds both the validation error and the generated error message - so a custom feedback panel can have access to both.

Parameters:
error - validation error

getConvertedInput

public final java.lang.Object getConvertedInput()
Gets the converted input. The converted input is set earlier though the implementation of convertInput().

Returns:
value of input possibly converted into an appropriate type

setConvertedInput

public final void setConvertedInput(java.lang.Object convertedInput)
Sets the converted input. This method is typically not called by clients, unless they override convertInput(), in which case they should call this method to update the input for this component instance.

Parameters:
convertedInput - the converted input

getForm

public Form getForm()
Returns:
The parent form for this form component

getInput

public java.lang.String getInput()
Gets the request parameter for this component as a string.

Returns:
The value in the request for this component

getInputAsArray

public java.lang.String[] getInputAsArray()
Gets the request parameters for this component as strings.

Returns:
The values in the request for this component

getInputName

public java.lang.String getInputName()
Gets the string to be used for the name attribute of the form element. Generated using the path from the form to the component, excluding the form itself. Override it if you want even a smaller name. E.g. if you know for sure that the id is unique within a form.

Returns:
The string to use as the form element's name attribute

getRawInput

public final java.lang.String getRawInput()
Use hasRawInput() to check if this component has raw input because null can mean 2 things: It doesn't have rawinput or the rawinput is really null.

Returns:
The raw form input that is stored for this formcomponent

getType

public final java.lang.Class getType()
Returns:
the type to use when updating the model for this form component

getValidatorKeyPrefix

public java.lang.String getValidatorKeyPrefix()
Returns:
prefix used when constructing validator key messages
See Also:
Form.getValidatorKeyPrefix()

getValidators

public final java.util.List getValidators()
Gets an unmodifiable list of validators for this FormComponent.

Returns:
List of validators

getValue

public final java.lang.String getValue()
Gets current value for a form component, which can be either input data entered by the user, or the component's model object if no input was provided.

Returns:
The value

hasRawInput

public final boolean hasRawInput()
Returns whether this component has raw input. Raw input is unconverted input straight from the client.

Returns:
boolean whether this component has raw input.

inputChanged

public final void inputChanged()
Used by Form to tell the FormComponent that a new user input is available


invalid

public final void invalid()
Indicate that validation of this form component failed.


isInputNullable

public boolean isInputNullable()
Gets whether this component's input can be null. By default, components that do not get input will have null values passed in for input. However, component TextField is an example (possibly the only one) that never gets a null passed in, even if the field is left empty UNLESS it had attribute disabled="disabled" set.

Returns:
True if this component's input can be null. Returns true by default.

isMultiPart

public boolean isMultiPart()
Returns:
True if this component encodes data in a multipart form submit

isPersistent

public final boolean isPersistent()
Returns:
True if this component supports persistence AND it has been asked to persist itself with setPersistent().

isRequired

public boolean isRequired()
Returns:
whether or not this component's value is required

isValid

public final boolean isValid()
Gets whether this component is 'valid'. Valid in this context means that no validation errors were reported the last time the form component was processed. This variable not only is convenient for 'business' use, but is also necessary as we don't want the form component models updated with invalid input.

Returns:
valid whether this component is 'valid'

processChildren

public boolean processChildren()
Description copied from interface: IFormVisitorParticipant
Should children be traversed during visiting or should only the siblings be processed.

Specified by:
processChildren in interface IFormVisitorParticipant
Returns:
true if children should be traversed during form processing; false if only the siblings should be processed.
See Also:
IFormVisitorParticipant.processChildren()

processInput

public final void processInput()
This method will retrieve the request parameter, validate it, and if valid update the model. These are the same steps as would be performed by the form. This is useful when a formcomponent is used outside a form.


setLabel

public FormComponent setLabel(IModel labelModel)
The value will be made available to the validator property by means of ${label}. It does not have any specific meaning to FormComponent itself.

Parameters:
labelModel -
Returns:
this for chaining

setModelValue

public void setModelValue(java.lang.String value)
Deprecated. call or override setModelValue(String[])

Sets the value for a form component this value will be split the string with VALUE_SEPARATOR and calls setModelValue(String[]) with that.

Parameters:
value - The value

setModelValue

public void setModelValue(java.lang.String[] value)
Sets the value for a form component.

Parameters:
value - The value

setPersistent

public final FormComponent setPersistent(boolean persistent)
Sets whether this component is to be persisted.

Parameters:
persistent - True if this component is to be persisted.
Returns:
this for chaining

setRequired

public final FormComponent setRequired(boolean required)
Sets the required flag

Parameters:
required -
Returns:
this for chaining

setType

public final FormComponent setType(java.lang.Class type)
Sets the type that will be used when updating the model for this component. If no type is specified String type is assumed.

Parameters:
type -
Returns:
this for chaining

updateModel

public void updateModel()
Updates this components model from the request, it expects that the object is already converted through the convertInput() call that is called by the validate() method when a form is being processed. By default it just does this:
 setModelObject(getConvertedInput());
 
DO NOT CALL THIS METHOD DIRECTLY UNLESS YOU ARE SURE WHAT YOU ARE DOING. USUALLY UPDATING YOUR MODEL IS HANDLED BY THE FORM, NOT DIRECTLY BY YOU.


valid

public final void valid()
Called to indicate that the user input is valid.


validate

public final void validate()
Performs full validation of the form component, which consists of calling validateRequired(), convertInput(), and validateValidators(). This method should only be used if the form component needs to be fully validated outside the form process.


convertInput

protected void convertInput()
Converts and validates the conversion of the raw input string into the object specified by getType() and records any errors. Converted value is available through getConvertedInput()


convertValue

protected java.lang.Object convertValue(java.lang.String[] value)
                                 throws ConversionException
Subclasses should overwrite this if the conversion is not done through the type field and the IConverter. WARNING: this method may be removed in future versions. If conversion fails then a ConversionException should be thrown

Parameters:
value - The value can be the getInput() or through a cookie
Returns:
The converted value. default returns just the given value
Throws:
ConversionException - If input can't be converted

getBehaviors

protected java.util.List getBehaviors(java.lang.Class type)
Description copied from class: Component
Gets the subset of the currently coupled IBehaviors that are of the provided type as a unmodifiable list or null if there are no behaviors attached. Returns an empty list rather than null if there are no behaviors coupled to this component.

Overrides:
getBehaviors in class Component
Parameters:
type - The type or null for all
Returns:
The subset of the currently coupled behaviors that are of the provided type as a unmodifiable list or null
See Also:
Component.getBehaviors(java.lang.Class)

getModelValue

protected java.lang.String getModelValue()
Returns:
Value to return when model value is needed

inputAsInt

protected final int inputAsInt()
Gets the request parameter for this component as an int.

Returns:
The value in the request for this component

inputAsInt

protected final int inputAsInt(int defaultValue)
Gets the request parameter for this component as an int, using the given default in case no corresponding request parameter was found.

Parameters:
defaultValue - Default value to return if request does not have an integer for this component
Returns:
The value in the request for this component

inputAsIntArray

protected final int[] inputAsIntArray()
Gets the request parameters for this component as ints.

Returns:
The values in the request for this component

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

onComponentTag

protected void onComponentTag(ComponentTag tag)
Processes the component tag.

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

onDetach

protected void onDetach()
Sets the temporary converted input value to null.

Overrides:
onDetach in class LabeledWebMarkupContainer
See Also:
Component.onDetach()

onDisabled

protected void onDisabled(ComponentTag tag)
Called by onComponentTag(ComponentTag) when the component is disabled. By default, this method will add a disabled="disabled" attribute to the tag. Components may override this method to tweak the tag as they think is fit.

Parameters:
tag - the tag that is being rendered

onInvalid

protected void onInvalid()
Handle invalidation


onValid

protected void onValid()
Handle validation


shouldTrimInput

protected boolean shouldTrimInput()
Determines whether or not this component should trim its input prior to processing it. The default value is true

Returns:
True if the input should be trimmed.

trim

protected final java.lang.String trim(java.lang.String string)
Trims the input according to shouldTrimInput()

Parameters:
string -
Returns:
trimmed input if shouldTrimInput() returns true, unchanged input otherwise

supportsPersistence

protected boolean supportsPersistence()
Returns:
True if this type of FormComponent can be persisted.

validateRequired

protected final void validateRequired()
Checks if the raw input value is not null if this component is required.


validateValidators

protected final void validateValidators()
Validates this component using the component's validators.



Copyright © 2004-2010 Apache Software Foundation. All Rights Reserved.