📄 formcomponent.java
字号:
return this; } /** * Sets the required flag * * @param required * @return this for chaining */ public final FormComponent setRequired(final boolean required) { if (!required && getType() != null && getType().isPrimitive()) { throw new WicketRuntimeException( "FormComponent can't be not required when the type is primitive class: " + this); } if (required != isRequired()) { addStateChange(new RequiredStateChange()); } setFlag(FLAG_REQUIRED, required); return this; } /** * Sets the type that will be used when updating the model for this component. If no type is * specified String type is assumed. * * @param type * @return this for chaining */ public final FormComponent setType(Class type) { typeName = type == null ? null : type.getName(); if (type != null && type.isPrimitive()) { setRequired(true); } return this; } /** * 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: * * <pre> * setModelObject(getConvertedInput()); * </pre> * * 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. */ public void updateModel() { setModelObject(getConvertedInput()); } /** * Called to indicate that the user input is valid. */ public final void valid() { clearInput(); onValid(); } /** * 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. */ public final void validate() { validateRequired(); if (isValid()) { convertInput(); if (isValid() && isRequired() && getConvertedInput() == null && isInputNullable()) { reportRequiredError(); } if (isValid()) { validateValidators(); } } } /** * @param validator * The validator to add to the validators Object (which may be an array of * IValidators or a single instance, for efficiency) */ private void validators_add(final IValidator validator) { if (validators == null) { validators = validator; } else { // Get current list size final int size = validators_size(); // Create array that holds size + 1 elements final IValidator[] validators = new IValidator[size + 1]; // Loop through existing validators copying them for (int i = 0; i < size; i++) { validators[i] = validators_get(i); } // Add new validator to the end validators[size] = validator; // Save new validator list this.validators = validators; } } /** * Gets validator from validators Object (which may be an array of IValidators or a single * instance, for efficiency) at the given index * * @param index * The index of the validator to get * @return The validator */ private IValidator validators_get(int index) { if (validators == null) { throw new IndexOutOfBoundsException(); } if (validators instanceof IValidator[]) { return ((IValidator[])validators)[index]; } return (IValidator)validators; } /** * @return The number of validators in the validators Object (which may be an array of * IValidators or a single instance, for efficiency) */ private int validators_size() { if (validators == null) { return 0; } if (validators instanceof IValidator[]) { return ((IValidator[])validators).length; } return 1; } /** * Converts and validates the conversion of the raw input string into the object specified by * {@link FormComponent#getType()} and records any errors. Converted value is available through * {@link FormComponent#getConvertedInput()} */ protected void convertInput() { if (typeName == null) { try { convertedInput = convertValue(getInputAsArray()); } catch (ConversionException e) { ValidationError error = new ValidationError(); if (e.getResourceKey() != null) { error.addMessageKey(e.getResourceKey()); } if (e.getTargetType() != null) { error.addMessageKey("ConversionError." + Classes.simpleName(e.getTargetType())); } error.addMessageKey("ConversionError"); reportValidationError(e, error); } } else { final IConverter converter = getConverter(getType()); try { convertedInput = converter.convertToObject(getInput(), getLocale()); } catch (ConversionException e) { ValidationError error = new ValidationError(); if (e.getResourceKey() != null) { error.addMessageKey(e.getResourceKey()); } String simpleName = Classes.simpleName(getType()); error.addMessageKey("IConverter." + simpleName); error.addMessageKey("IConverter"); error.setVariable("type", simpleName); reportValidationError(e, error); } } } private void reportValidationError(ConversionException e, ValidationError error) { final Locale locale = e.getLocale(); if (locale != null) { error.setVariable("locale", locale); } error.setVariable("exception", e); Format format = e.getFormat(); if (format instanceof SimpleDateFormat) { error.setVariable("format", ((SimpleDateFormat)format).toLocalizedPattern()); } Map variables = e.getVariables(); if (variables != null) { error.getVariables().putAll(variables); } error((IValidationError)error); } /** * Subclasses should overwrite this if the conversion is not done through the type field and the * IConverter. <strong>WARNING: this method may be removed in future versions.</strong> * * If conversion fails then a ConversionException should be thrown * * @param value * The value can be the getInput() or through a cookie * * @return The converted value. default returns just the given value * @throws ConversionException * If input can't be converted */ protected Object convertValue(String[] value) throws ConversionException { return value != null && value.length > 0 && value[0] != null ? value[0].trim() : null; } /** * @see org.apache.wicket.Component#getBehaviors(java.lang.Class) */ protected List getBehaviors(Class type) { // List return super.getBehaviors(type); } /** * @return Value to return when model value is needed */ protected String getModelValue() { return getModelObjectAsString(); } /** * Gets the request parameter for this component as an int. * * @return The value in the request for this component */ protected final int inputAsInt() { final String string = getInput(); try { return Integer.parseInt(string); } catch (NumberFormatException e) { throw new IllegalArgumentException( exceptionMessage("Internal error. Request string '" + string + "' not a valid integer")); } } /** * Gets the request parameter for this component as an int, using the given default in case no * corresponding request parameter was found. * * @param defaultValue * Default value to return if request does not have an integer for this component * @return The value in the request for this component */ protected final int inputAsInt(final int defaultValue) { final String string = getInput(); if (string != null) { try { return Integer.parseInt(string); } catch (NumberFormatException e) { throw new IllegalArgumentException(exceptionMessage("Request string '" + string + "' is not a valid integer")); } } else { return defaultValue; } } /** * Gets the request parameters for this component as ints. * * @return The values in the request for this component */ protected final int[] inputAsIntArray() { final String[] strings = getInputAsArray(); if (strings != null) { final int[] ints = new int[strings.length]; for (int i = 0; i < strings.length; i++) { ints[i] = Integer.parseInt(strings[i]); } return ints; } return null; } /** * @see org.apache.wicket.Component#internalOnModelChanged() */ protected void internalOnModelChanged() { // If the model for this form component changed, we should make it // valid again because there can't be any invalid input for it anymore. valid(); } /** * Processes the component tag. * * @param tag * Tag to modify * @see org.apache.wicket.Component#onComponentTag(ComponentTag) */ protected void onComponentTag(final ComponentTag tag) { tag.put("name", getInputName()); if (!isEnabled() || !isEnableAllowed()) { onDisabled(tag); } super.onComponentTag(tag); } /** * Sets the temporary converted input value to null. * * @see org.apache.wicket.Component#onDetach() */ protected void onDetach() { super.onDetach(); convertedInput = null; } /** * Called by {@link #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. * * @param tag * the tag that is being rendered */ protected void onDisabled(final ComponentTag tag) { tag.put("disabled", "disabled"); } /** * Handle invalidation */ protected void onInvalid() { } /** * Handle validation */ protected void onValid() { } /** * @return True if this type of FormComponent can be persisted. */ protected boolean supportsPersistence() { return false; } /** * Checks if the raw input value is not null if this component is required. */ protected final void validateRequired() { if (!checkRequired()) { reportRequiredError(); } } /** * Reports required error against this component */ private void reportRequiredError() { error((IValidationError)new ValidationError().addMessageKey("Required")); } /** * Validates this component using the component's validators. */ protected final void validateValidators() { final int size = validators_size(); final IValidatable validatable = new ValidatableAdapter(); int i = 0; IValidator validator = null; boolean isNull = getConvertedInput() == null; try { for (i = 0; i < size; i++) { validator = validators_get(i); if (isNull == false || validator instanceof INullAcceptingValidator) { validator.validate(validatable); } if (!isValid()) { break; } } } catch (Exception e) { throw new WicketRuntimeException("Exception '" + e + "' occurred during validation " + validator.getClass().getName() + " on component " + getPath(), e); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -