- Type Parameters:
T
- The model object type
- All Implemented Interfaces:
Serializable
,Iterable<Component>
,IEventSink
,IEventSource
,IFeedbackContributor
,IConverterLocator
,IGenericComponent<T,
,FormComponent<T>> IMetadataContext<Serializable,
,Component> IFormModelUpdateListener
,IFormVisitorParticipant
,ILabelProvider<String>
,IHeaderContributor
,IRequestableComponent
,IHierarchical<Component>
,IClusterable
- Direct Known Subclasses:
AbstractChoice
,AbstractOptions
,AbstractTextComponent
,Button
,CheckBox
,CheckGroup
,FileUploadField
,FormComponentPanel
,RadioGroup
,Select
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:
- ${input}: the input the user did give
- ${name}: the name of the component that failed
- ${label}: the label of the component
- Author:
- Jonathan Locke, Eelco Hillenius, Johan Compagner, Igor Vaynberg (ivaynberg)
- See Also:
-
Field Summary
Modifier and TypeFieldDescriptionprotected static final short
Make empty strings null values boolean.static final String
The value separatorFields inherited from class org.apache.wicket.Component
ENABLE, FLAG_INITIALIZED, FLAG_RESERVED1, FLAG_RESERVED2, FLAG_RESERVED3, FLAG_RESERVED4, FLAG_RESERVED5, FLAG_RESERVED8, PARENT_PATH, PATH_SEPARATOR, RENDER, RFLAG_CONTAINER_DEQUEING, RFLAG_CONTAINER_HAS_REMOVALS
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionfinal FormComponent<T>
add
(IValidator<? super T> validator) Adds a validator to this form componentfinal FormComponent<T>
add
(IValidator<? super T>... validators) Adds a validator to this form component.boolean
Checks if the form component's 'required' requirement is met by first checkingisRequired()
to see if it has to check for requirement.void
Clears the user input.void
Converts and validates the conversion of the raw input string into the object specified bygetType()
and records any thrownConversionException
s.protected T
convertValue
(String[] value) Subclasses should overwrite this if the conversion is not done through the type field and theIConverter
.void
error
(IValidationError error) Reports a validation error against this form component.final T
Gets the converted input.final String
Gets the string the component would use as a label when one was requested but no label model was set viaLabeledWebMarkupContainer.getLabel()
.final String
getDefaultLabel
(String defaultValue) Gets the string the component would use as a label when one was requested but no label model was set viaLabeledWebMarkupContainer.getLabel()
.Form<?>
getForm()
getInput()
Gets the request parameter for this component as a string.String[]
Gets the request parameters for this component as strings.Gets the string to be used for the name attribute of the form element.protected String
protected List<StringValue>
getParameterValues
(String inputName) Reads the value(s) of the request parameter with name inputName from either the query parameters for GET method or the request body for POST method.final String
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.getType()
final List<IValidator<? super T>>
Gets an unmodifiable list of validators for this FormComponent.final 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.final boolean
Returns whether this component has raw input.protected final int
Gets the request parameter for this component as an int.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.protected final int[]
Gets the request parameters for this component as ints.final void
Used by Form to tell the FormComponent that a new user input is availableprotected void
THIS METHOD IS NOT PART OF THE WICKET PUBLIC API.final void
invalid()
Indicate that validation of this form component failed.boolean
Gets whether this component's input can be null.boolean
boolean
final boolean
isValid()
Gets whether this component is 'valid'.final IValidatable<T>
Creates an IValidatable that can be used to validate this form component.protected ValidationError
This method is called, when the validation triggered byconvertInput()
failed with aConversionException
, to construct aValidationError
based on the exception.protected void
Called on all visible components before any component is rendered.protected void
Processes the component tag.protected void
onDetach()
Sets the temporary converted input value to null.protected void
onDisabled
(ComponentTag tag) Called byonComponentTag(ComponentTag)
when the component is disabled.protected void
Handle invalidationprotected void
onValid()
Handle validationboolean
Should children be traversed during visiting or should only the siblings be processed.final void
This method will retrieve the request parameter, validate it, and if valid update the model.final FormComponent<T>
remove
(IValidator<? super T> validator) Removes a validator from the form component.protected void
Reports required error against this componentfinal void
setConvertedInput
(T convertedInput) Sets the converted input.The value will be made available to the validator property by means of ${label}.void
setModelValue
(String[] value) THIS METHOD IS NOT PART OF THE WICKET PUBLIC API.final FormComponent<T>
setRequired
(boolean required) Sets the required flagSets the type that will be used when updating the model for this component.protected boolean
Determines whether or not this component should trim its input prior to processing it.protected String
Trims the input according toshouldTrimInput()
final void
updateAutoLabels
(AjaxRequestTarget target) Deprecated, for removal: This API element is subject to removal in a future version.final void
updateAutoLabels
(IPartialPageRequestHandler target, boolean checkAuto) Updates auto label css classes such as error/required during ajax updates when the labels may not be directly repainted in the response.static <S> void
updateCollectionModel
(FormComponent<Collection<S>> formComponent) Update the model of aFormComponent
containing aCollection
.void
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.final 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 final void
Checks if the raw input value is not null if this component is required.protected final void
Validates this component using the component's validators.static <R> R
visitComponentsPostOrder
(Component component, IVisitor<Component, R> visitor) Visits any form components inside component if it is a container, or component itself if it is itself a form componentstatic <R> R
visitFormComponentsPostOrder
(Component component, IVisitor<? extends FormComponent<?>, R> visitor) Visits any form components inside component if it is a container, or component itself if it is itself a form componentMethods inherited from class org.apache.wicket.markup.html.form.LabeledWebMarkupContainer
getLabel
Methods inherited from class org.apache.wicket.markup.html.WebMarkupContainer
getWebApplication, getWebPage, getWebRequest, getWebResponse, getWebSession
Methods inherited from class org.apache.wicket.MarkupContainer
add, addDequeuedComponent, addOrReplace, autoAdd, canDequeueTag, contains, dequeue, dequeue, dequeuePreamble, findChildComponent, findComponentToDequeue, get, getAssociatedMarkup, getAssociatedMarkupStream, getMarkup, getMarkupType, getRegionMarkup, internalAdd, internalInitialize, iterator, iterator, newDequeueContext, onComponentTagBody, onInitialize, onRender, queue, remove, remove, removeAll, renderAll, renderAssociatedMarkup, renderNext, replace, setDefaultModel, size, stream, streamChildren, toString, toString, visitChildren, visitChildren
Methods inherited from class org.apache.wicket.Component
add, addStateChange, beforeRender, canCallListener, canCallListenerAfterExpiry, checkComponentTag, checkComponentTagAttribute, checkHierarchyChange, clearOriginalDestination, configure, continueToOriginalDestination, createConverter, debug, detach, detachModel, detachModels, determineVisibility, error, exceptionMessage, fatal, findMarkupStream, findPage, findParent, findParentWithAssociatedMarkup, getAjaxRegionMarkupId, getApplication, getBehaviorById, getBehaviorId, getBehaviors, getBehaviors, getClassRelativePath, getConverter, getDefaultModel, getDefaultModelObject, getDefaultModelObjectAsString, getDefaultModelObjectAsString, getEscapeModelStrings, getFeedbackMessages, getFlag, getId, getInnermostModel, getInnermostModel, getLocale, getLocalizer, getMarkup, getMarkupAttributes, getMarkupId, getMarkupId, getMarkupIdFromMarkup, getMarkupIdImpl, getMarkupSourcingStrategy, getMarkupTag, getMetaData, getModelComparator, getOutputMarkupId, getOutputMarkupPlaceholderTag, getPage, getPageRelativePath, getParent, getPath, getRenderBodyOnly, getRequest, getRequestCycle, getRequestFlag, getResponse, getSession, getSizeInBytes, getStatelessHint, getString, getString, getString, getStyle, getVariation, hasBeenRendered, hasErrorMessage, hasFeedbackMessage, info, initModel, internalRenderComponent, internalRenderHead, isActionAuthorized, isAuto, isBehaviorAccepted, isEnableAllowed, isEnabled, isEnabledInHierarchy, isIgnoreAttributeModifier, isInitialized, isRenderAllowed, isRendering, isStateless, isVersioned, isVisibilityAllowed, isVisible, isVisibleInHierarchy, markRendering, modelChanged, modelChanging, newMarkupSourcingStrategy, onAfterRender, onConfigure, onEvent, onModelChanged, onModelChanging, onReAdd, onRemove, redirectToInterceptPage, remove, remove, render, renderComponentTag, rendered, renderHead, renderPart, renderPlaceholderTag, replaceComponentTagBody, replaceWith, sameInnermostModel, sameInnermostModel, send, setAuto, setDefaultModelObject, setEnabled, setEscapeModelStrings, setFlag, setIgnoreAttributeModifier, setMarkup, setMarkupId, setMarkupIdImpl, setMetaData, setOutputMarkupId, setOutputMarkupPlaceholderTag, setParent, setRenderBodyOnly, setResponsePage, setResponsePage, setResponsePage, setVersioned, setVisibilityAllowed, setVisible, success, urlFor, urlFor, urlFor, urlForListener, urlForListener, visitParents, visitParents, warn, wrap
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.apache.wicket.IGenericComponent
getDefaultModel, getDefaultModelObject, getModel, getModelObject, setDefaultModel, setDefaultModelObject, setModel, setModelObject
Methods inherited from interface java.lang.Iterable
forEach, spliterator
-
Field Details
-
VALUE_SEPARATOR
The value separator- See Also:
-
FLAG_CONVERT_EMPTY_INPUT_STRING_TO_NULL
Make empty strings null values boolean. Used by AbstractTextComponent subclass.- See Also:
-
-
Constructor Details
-
FormComponent
- See Also:
-
FormComponent
- Parameters:
id
-model
-- See Also:
-
-
Method Details
-
onBeforeRender
Description copied from class:Component
Called on all visible components before any component is rendered.NOTE: If you override this, you *must* call super.onBeforeRender() within your implementation. Because this method is responsible for cascading
Changes to the component tree can be made only before calling super.onBeforeRender().Component.onBeforeRender()
call to its children it is strongly recommended that super call is made at the end of the override.- Overrides:
onBeforeRender
in classComponent
- See Also:
-
visitFormComponentsPostOrder
public static <R> R visitFormComponentsPostOrder(Component component, IVisitor<? extends FormComponent<?>, R> visitor) Visits any form components inside component if it is a container, or component itself if it is itself a form component- Type Parameters:
R
- the type of the visitor's result- Parameters:
component
- starting point of the traversalvisitor
- The visitor to call- Returns:
- the visitor's result
-
visitComponentsPostOrder
Visits any form components inside component if it is a container, or component itself if it is itself a form component- Type Parameters:
R
- the type of the visitor's result- Parameters:
component
- starting point of the traversalvisitor
- The visitor to call- Returns:
- the visitor's result
-
getDefaultLabel
Gets the string the component would use as a label when one was requested but no label model was set viaLabeledWebMarkupContainer.getLabel()
. The value of this string is usually set in a property file; if the value is not set the default value equivalent to component id will be returned.- Returns:
- localized label
-
getDefaultLabel
Gets the string the component would use as a label when one was requested but no label model was set viaLabeledWebMarkupContainer.getLabel()
. The value of this string is usually set in a property file; if the value is not set thedefaultValue
will be returned.- Parameters:
defaultValue
-- Returns:
- localized label
-
add
Adds a validator to this form component- Parameters:
validator
- validator to be added- Returns:
this
for chaining- Throws:
IllegalArgumentException
- if validator is null- See Also:
-
remove
Removes a validator from the form component.- Parameters:
validator
- validator- Returns:
- form component for chaining
- Throws:
IllegalArgumentException
- if validator is null or not found- See Also:
-
add
Adds a validator to this form component.- Parameters:
validators
- The validator(s) to be added- Returns:
- This
- Throws:
IllegalArgumentException
- if validator is null- See Also:
-
checkRequired
Checks if the form component's 'required' requirement is met by first checkingisRequired()
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 StringStrings.isEmpty(CharSequence)
Subclasses that overwrite this method should also call
isRequired()
first.- Returns:
- true if the 'required' requirement is met, false otherwise
- See Also:
-
clearInput
Clears the user input. -
error
Reports a validation error against this form component. The actual error is reported by creating aValidationErrorFeedback
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
Gets the converted input. The converted input is set earlier though the implementation ofconvertInput()
.FormComponentPanel
often access this method when constructing their converted input value which is often the combination of converted values of the embedded FormComponents To access the model object resulted by the full form processing, useIGenericComponent.getModelObject()
instead, that is an generified version ofComponent.getDefaultModelObject()
- Returns:
- value of input possibly converted into an appropriate type
-
setConvertedInput
Sets the converted input. This method is typically not called by clients, unless they overrideconvertInput()
, in which case they should call this method to update the input for this component instance.- Parameters:
convertedInput
- the converted input
-
getForm
- Returns:
- The parent form for this form component
-
getInput
Gets the request parameter for this component as a string.- Returns:
- The value in the request for this component
-
getInputAsArray
Gets the request parameters for this component as strings.- Returns:
- The values in the request for this component
-
getParameterValues
Reads the value(s) of the request parameter with name inputName from either the query parameters for GET method or the request body for POST method.- Parameters:
inputName
- The name of the request parameter- Returns:
- The parameter's value(s)
-
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
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
- Returns:
- the type to use when updating the model for this form component
-
getValidatorKeyPrefix
- Returns:
- prefix used when constructing validator key messages
- See Also:
-
getValidators
Gets an unmodifiable list of validators for this FormComponent.- Returns:
- List of validators
-
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
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
Used by Form to tell the FormComponent that a new user input is available -
invalid
Indicate that validation of this form component failed. -
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 has attributedisabled="disabled"
set.- Returns:
- True if this component's input can be null. Returns true by default.
-
isMultiPart
- Returns:
- True if this component encodes data in a multipart form submit
-
isRequired
- Returns:
- whether or not this component's value is required
-
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
Description copied from interface:IFormVisitorParticipant
Should children be traversed during visiting or should only the siblings be processed.- Specified by:
processChildren
in interfaceIFormVisitorParticipant
- Returns:
- true if children should be traversed during form processing; false if only the siblings should be processed.
- See Also:
-
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
The value will be made available to the validator property by means of ${label}. It does not have any specific meaning to FormComponent itself.- Overrides:
setLabel
in classLabeledWebMarkupContainer
- Parameters:
labelModel
-- Returns:
- this for chaining
-
setModelValue
THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT! Sets the value for a form component.- Parameters:
value
- The value
-
setRequired
Sets the required flag- Parameters:
required
-- Returns:
- this for chaining
-
setType
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
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.- Specified by:
updateModel
in interfaceIFormModelUpdateListener
-
valid
Called to indicate that the user input is valid. -
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
Converts and validates the conversion of the raw input string into the object specified bygetType()
and records any thrownConversionException
s. Converted value is available throughgetConvertedInput()
.Usually the user should do custom conversions by specifying an
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.IConverter
by registering it with the application by overridingApplication.getConverterLocator()
, or at the component level by overridingComponent.getConverter(Class)
. -
newValidationError
This method is called, when the validation triggered byconvertInput()
failed with aConversionException
, to construct aValidationError
based on the exception.Override this method to modify the ValidationError object, e.g. add a custom variable for message substitution:
new FormComponent<T>(id) { protected ValidationError newValidationError(ConversionException cause) { return super.newValidationError(cause).setVariable("foo", foovalue); } };
- Parameters:
cause
- the original cause- Returns:
ValidationError
-
convertValue
Subclasses should overwrite this if the conversion is not done through the type field and theIConverter
. 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
-
getModelValue
- Returns:
- Value to return when model value is needed
-
inputAsInt
Gets the request parameter for this component as an int.- Returns:
- The value in the request for this component
-
inputAsInt
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
Gets the request parameters for this component as ints.- Returns:
- The values in the request for this component
-
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 classComponent
- See Also:
-
onComponentTag
Processes the component tag.- Overrides:
onComponentTag
in classComponent
- Parameters:
tag
- Tag to modify- See Also:
-
onDetach
Sets the temporary converted input value to null.- Overrides:
onDetach
in classLabeledWebMarkupContainer
- See Also:
-
onDisabled
Called byonComponentTag(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
Handle invalidation -
onValid
Handle validation -
shouldTrimInput
Determines whether or not this component should trim its input prior to processing it. The default value istrue
- Returns:
- True if the input should be trimmed.
-
trim
Trims the input according toshouldTrimInput()
- Parameters:
string
-- Returns:
- trimmed input if
shouldTrimInput()
returns true, unchanged input otherwise
-
validateRequired
Checks if the raw input value is not null if this component is required. -
reportRequiredError
Reports required error against this component -
validateValidators
Validates this component using the component's validators. -
newValidatable
Creates an IValidatable that can be used to validate this form component. This validatable incorporates error key lookups that correspond to this form component. This method is useful when validation needs to happen outside the regular validation workflow but error messages should still be properly reported against the form component.- Returns:
- IValidatable
for this form component
-
updateAutoLabels
Updates auto label css classes such as error/required during ajax updates when the labels may not be directly repainted in the response.- Parameters:
target
- TheIPartialPageRequestHandler
checkAuto
- if true then we check is the related auto-label is marked as auto before updating it.
-
updateAutoLabels
@Deprecated(since="9.17.0, 10.0.0", forRemoval=true) public final void updateAutoLabels(AjaxRequestTarget target) Deprecated, for removal: This API element is subject to removal in a future version.method in favor of the one receivingIPartialPageRequestHandler
-
updateCollectionModel
Update the model of aFormComponent
containing aCollection
. If the model object does not yet exists, a new suitable collection is filled with the converted input and used as the new model object. Otherwise the existing collection is modified in-place, thenIModel.setObject(Object)
is called with the same instance: it allows the Model to be notified of changes even whenModel.getObject()
returns a differentCollection
at every invocation.- Type Parameters:
S
- collection type- Parameters:
formComponent
- the form component to update- Throws:
WicketRuntimeException
- if the existing model object collection is unmodifiable and no setter exists- See Also:
-
IPartialPageRequestHandler