📄 form.java
字号:
*/ public void setMultiPart(boolean multiPart) { this.multiPart = multiPart; } /** * @see org.apache.wicket.Component#setVersioned(boolean) */ public final Component setVersioned(final boolean isVersioned) { super.setVersioned(isVersioned); // Search for FormComponents like TextField etc. visitFormComponents(new FormComponent.AbstractVisitor() { public void onFormComponent(final FormComponent formComponent) { formComponent.setVersioned(isVersioned); } }); return this; } /** * Convenient and typesafe way to visit all the form components on a form. * * @param visitor * The visitor interface to call */ public final void visitFormComponents(final FormComponent.IVisitor visitor) { visitChildren(FormComponent.class, new IVisitor() { public Object component(final Component component) { visitor.formComponent((FormComponent)component); return CONTINUE_TRAVERSAL; } }); visitChildrenInContainingBorder(visitor); } /** * Convenient and typesafe way to visit all the form components on a form postorder (deepest * first) * * @param visitor * The visitor interface to call */ public final void visitFormComponentsPostOrder(final FormComponent.IVisitor visitor) { FormComponent.visitFormComponentsPostOrder(this, visitor); visitChildrenInContainingBorder(visitor); } /** * TODO Post 1.2 General: Maybe we should re-think how Borders are implemented, because there * are just too many exceptions in the code base because of borders. This time it is to solve * the problem tested in BoxBorderTestPage_3 where the Form is defined in the box border and the * FormComponents are in the "body". Thus, the formComponents are not children of the form. They * are rather children of the border, as the Form itself. * * @param visitor * The {@link Component}.{@link IVisitor} used to visit the children. */ private void visitChildrenInContainingBorder(final FormComponent.IVisitor visitor) { if (getParent() instanceof Border) { MarkupContainer border = getParent(); Iterator iter = border.iterator(); while (iter.hasNext()) { Component child = (Component)iter.next(); if (child instanceof FormComponent) { visitor.formComponent((FormComponent)child); } } } } /** * Find out whether there is any registered error for a form component. * * @return whether there is any registered error for a form component */ private boolean anyFormComponentError() { final Object value = visitChildren(new IVisitor() { public Object component(final Component component) { if (component.hasErrorMessage()) { return STOP_TRAVERSAL; } // Traverse all children return CONTINUE_TRAVERSAL; } }); return value == IVisitor.STOP_TRAVERSAL ? true : false; } /** * Method for dispatching/calling a interface on a page from the given url. Used by * {@link org.apache.wicket.markup.html.form.Form#onFormSubmitted()} for dispatching events * * @param page * The page where the event should be called on. * @param url * The url which describes the component path and the interface to be called. */ private void dispatchEvent(final Page page, final String url) { RequestCycle rc = RequestCycle.get(); IRequestCycleProcessor processor = rc.getProcessor(); final RequestParameters requestParameters = processor.getRequestCodingStrategy().decode( new FormDispatchRequest(rc.getRequest(), url)); IRequestTarget rt = processor.resolve(rc, requestParameters); if (rt instanceof ListenerInterfaceRequestTarget) { ListenerInterfaceRequestTarget interfaceTarget = ((ListenerInterfaceRequestTarget)rt); interfaceTarget.getRequestListenerInterface().invoke(page, interfaceTarget.getTarget()); } else { throw new WicketRuntimeException( "Attempt to access unknown request listener interface " + requestParameters.getInterfaceName()); } } /** * @param validator * The form validator to add to the formValidators Object (which may be an array of * IFormValidators or a single instance, for efficiency) */ private void formValidators_add(final IFormValidator validator) { if (formValidators == null) { formValidators = validator; } else { // Get current list size final int size = formValidators_size(); // Create array that holds size + 1 elements final IFormValidator[] validators = new IFormValidator[size + 1]; // Loop through existing validators copying them for (int i = 0; i < size; i++) { validators[i] = formValidators_get(i); } // Add new validator to the end validators[size] = validator; // Save new validator list formValidators = validators; } } /** * Gets form validator from formValidators Object (which may be an array of IFormValidators or a * single instance, for efficiency) at the given index * * @param index * The index of the validator to get * @return The form validator */ private IFormValidator formValidators_get(int index) { if (formValidators == null) { throw new IndexOutOfBoundsException(); } if (formValidators instanceof IFormValidator[]) { return ((IFormValidator[])formValidators)[index]; } return (IFormValidator)formValidators; } /** * @return The number of form validators in the formValidators Object (which may be an array of * IFormValidators or a single instance, for efficiency) */ private int formValidators_size() { if (formValidators == null) { return 0; } if (formValidators instanceof IFormValidator[]) { return ((IFormValidator[])formValidators).length; } return 1; } /** * Visits the form's children FormComponents and inform them that a new user input is available * in the Request */ private void inputChanged() { visitFormComponentsPostOrder(new FormComponent.AbstractVisitor() { public void onFormComponent(final FormComponent formComponent) { if (formComponent.isVisibleInHierarchy()) { formComponent.inputChanged(); } } }); } /** * Persist (e.g. Cookie) FormComponent data to be reloaded and re-assigned to the FormComponent * automatically when the page is visited by the user next time. * * @see org.apache.wicket.markup.html.form.FormComponent#updateModel() */ private void persistFormComponentData() { // Cannot add cookies to request cycle unless it accepts them // We could conceivably be HTML over some other protocol! if (getRequestCycle() instanceof WebRequestCycle) { // The persistence manager responsible to persist and retrieve // FormComponent data final IValuePersister persister = getValuePersister(); // Search for FormComponent children. Ignore all other visitFormComponentsPostOrder(new FormComponent.AbstractVisitor() { public void onFormComponent(final FormComponent formComponent) { if (formComponent.isVisibleInHierarchy()) { // If peristence is switched on for that FormComponent // ... if (formComponent.isPersistent()) { // Save component's data (e.g. in a cookie) persister.save(formComponent); } else { // Remove component's data (e.g. cookie) persister.clear(formComponent); } } } }); } } /** * If a default IFormSubmittingComponent 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 component. 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. * * @param markupStream * The markup stream * @param openTag * The open tag for the body */ protected void appendDefaultButtonField(final MarkupStream markupStream, final ComponentTag openTag) { AppendingStringBuffer buffer = new AppendingStringBuffer(); // div that is not visible (but not display:none either) buffer.append("<div style=\"width:0px;height:0px;position:absolute;left:-100px;top:-100px;overflow:hidden\">"); // add an empty textfield (otherwise IE doesn't work) buffer.append("<input type=\"text\" autocomplete=\"false\"/>"); // add the submitting component final Component submittingComponent = (Component)defaultSubmittingComponent; buffer.append("<input type=\"submit\" name=\""); if (submittingComponent instanceof FormComponent) { buffer.append(((FormComponent)submittingComponent).getInputName()); } else { buffer.append(submittingComponent.getPath()); } buffer.append("\" onclick=\" var b=Wicket.$('"); buffer.append(submittingComponent.getMarkupId()); buffer.append("'); if (typeof(b.onclick) != 'undefined') { var r = b.onclick.bind(b)(); if (r != false) b.click(); } else { b.click(); }; return false;\" "); buffer.append(" />"); // close div buffer.append("</div>"); getResponse().write(buffer); } /** * 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. */ protected void beforeUpdateFormComponentModels() { } /** * 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. * <p> * This implementation first finds out whether the form processing was triggered by a nested * IFormSubmittingComponent of this form. If that is the case, that component's onSubmit is * called first. * </p> * <p> * Regardless of whether a submitting component was found, the form's onSubmit method is called * next. * </p> * * @param submittingComponent * the component 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) */ protected void delegateSubmit(IFormSubmittingComponent submittingComponent) { // when the given submitting component is not null, it means that it was the // submitting component Form formToProcess = this; if (submittingComponent != null) { submittingComponent.onSubmit(); // use the form which the submittingComponent has submitted for further processing formToProcess = submittingComponent.getForm(); } // Model was successfully updated with valid data formToProcess.onSubmit(); // call onSubmit on nested forms formToProcess.visitChildren(Form.class, new IVisitor() { public Object component(Component component) { Form form = (Form)component; if (form.isEnabled() && form.isEnableAllowed() && form.isVisibleInHierarchy()) { form.onSubmit(); return IVisitor.CONTINUE_TRAVERSAL; } return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER; } }); } /** * Returns the HiddenFieldId which will be used as the name and id property of the hiddenfield * that is generated for event dispatches. * * @return The name and id of the hidden field. */ protected final String getHiddenFieldId() { return getJavascriptId() + "_hf_0"; } /** * Returns the javascript/css id of this form that will be used to generated the id="xxx" * attribute. * * @return The javascript/css id of this form. * @deprecated use {@link #getMarkupId()} */ protected final String getJavascriptId() { return getMarkupId(); } /** * Gets the method used to submit the form. Defaults to either what is explicitly defined in the * markup or 'post'. Override this if you have a requirement to alter this behavior. * * @return the method used to submit the form. */ protected String getMethod() { String method = getMarkupAttributes().getString("method"); return (method != null) ? method : METHOD_POST; } protected boolean getStatelessHint() { return false; } /** * Gets the form component persistence manager; it is lazy loaded. * * @return The form component value persister */ protected IValuePersister getValuePersister() { return new CookieValuePersister(); } /** * Handles multi-part processing of the submitted data. * * WARNING * * If this method is overridden it can break {@link FileUploadField}s on this form * * @return false if form is multipart and upload failed */ protected boolean handleMultiPart() { if (multiPart) { // Change the request to a multipart web request so parameters are // parsed out correctly try { final WebRequest multipartWebRequest = ((WebRequest)getRequest()).newMultipartWebRequest(getMaxSize()); getRequestCycle().setRequest(multipartWebRequest); } catch (WicketRuntimeException wre) { if (wre.getCause() == null || !(wre.getCause() instanceof FileUploadException)) { throw wre; } FileUploadException e = (FileUploadException)wre.getCause(); // Create model with exception and maximum size values final Map model = new HashMap(); model.put("exception", e); model.put("maxSize", getMaxSize()); if (e instanceof SizeLimitExceededException) { // Resource key should be <form-id>.uploadTooLarge to // override default message final String defaultValue = "Upload must be less than " + getMaxSize(); String msg = getString(getId() + "." + UPLOAD_TOO_LARGE_RESOURCE_KEY, Model.valueOf(model), defaultValue); error(msg); } else { // Resource key should be <form-id>.uploadFailed to override // default message final String defaultValue = "Upload failed: " + e.getLocalizedMessage(); String msg = getString(getId() + "." + UPLOAD_FAILED_RESOURCE_KEY, Model.valueOf(model), defaultValue); error(msg); log.warn(msg, e); } // don't process the form if there is a FileUploadException return false; } } return true; } /**
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -