Class NativeForm
- All Implemented Interfaces:
AttachNotifier,DetachNotifier,HasComponents,HasComponentsOfType<Component>,HasElement,HasEnabled,HasSize,HasStyle,HasText,Serializable
<form> element.
A native form is submitted by the browser itself: when the user activates a
submit button inside it, the browser sends the values of the named fields
(Input.setName(String)) to the action URL
with the given method and navigates to the
response. The values do not go through the server-side component state, so
use this for posting to an endpoint outside of Vaadin, such as the login
processing URL of Spring Security, rather than for editing data with a
Binder.
The browser submits only native form controls, such as
<input>, and form-associated custom elements with a form,
so use Input for the fields and NativeButton for the submit
button. Vaadin field components are not form-associated custom elements:
depending on the component they submit nothing, a formatted or internal value
instead of the field value, or only work by chance because of their internal
markup, and a Vaadin Button does not submit the form. None of this is
reported as an error.
Submitting the form makes the browser leave the current page, unless
a target sends the response to another
window or frame. The state of the Vaadin UI on the page is then lost. Keep in
mind what triggers a submit:
- A
NativeButtonsubmits the form unless its type is set toNativeButton.Type.BUTTON, becausesubmitis the HTML default. Set that type on every button in the form that should only run its click listeners. - Pressing Enter in an
Inputsubmits the form, even when the form has no submit button but only a single text field. - A click listener on a submit button races with the navigation: the browser may leave the page before the server has handled the click, so do not rely on it.
The form is submitted with NativeForm.Method.POST unless another method is set,
so that field values such as passwords do not end up in the URL, the browser
history and server logs. A POST to an endpoint protected by Spring Security
needs a CSRF token as a hidden Input named after the token parameter.
The login processing URL of a view configured with
VaadinSecurityConfigurer#loginView is exempt from this.
Input username = new Input();
username.setName("username");
username.setAutocomplete("username");
username.setRequiredIndicatorVisible(true);
Input password = new Input();
password.setType("password");
password.setName("password");
password.setAutocomplete("current-password");
password.setRequiredIndicatorVisible(true);
// Keep the password out of the Vaadin session, see below
password.setValueChangeMode(null);
NativeButton submit = new NativeButton("Log in");
submit.setType(NativeButton.Type.SUBMIT);
NativeForm form = new NativeForm(username, password, submit);
form.setAction("login");
HasValueAndElement.setRequiredIndicatorVisible(boolean) sets the native
required flag, so the browser does not submit the form while such an
input is empty, and Input.setAutocomplete(String) helps password
managers fill in a login form.
An Input sends its value to the server on every change by default, so
the value is also kept in the component state of the Vaadin session, which
may be serialized. Call setValueChangeMode(null) on an input for a
password or another secret that only the action URL should receive.
Forms can not be nested in HTML; the browser drops the inner
<form> tag. Adding a NativeForm directly to
another NativeForm therefore throws an
IllegalArgumentException.
- Since:
- 25.4
- Author:
- Vaadin Ltd
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumThe encoding of the form data when the form is submitted withNativeForm.Method.POST.static enumThe HTTP method the browser uses to submit the form.Nested classes/interfaces inherited from interface com.vaadin.flow.component.HasText
HasText.WhiteSpace -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new empty form that is submitted withNativeForm.Method.POST.NativeForm(Component... components) Creates a new form with the given children that is submitted withNativeForm.Method.POST. -
Method Summary
Modifier and TypeMethodDescriptionvoidadd(Collection<Component> components) Adds the given components as children of this component.voidaddComponentAtIndex(int index, Component component) Adds the given component as a child of this component at the specific index.bindChildren(Signal<List<S>> list, SerializableFunction<S, Component> childFactory) Binds a listSignalto this component using a child component factory.@Nullable StringGets the URL the browser submits the form to.@Nullable NativeForm.EnctypeGets how the browser encodes the form data when submitting it.@Nullable NativeForm.MethodGets the HTTP method the browser uses to submit the form.@Nullable AnchorTargetValueGets the window, tab or frame that shows the response when the form is submitted.voidReplaces the component in the container with another one without changing position.voidSets the URL the browser submits the form to.voidsetEnctype(@Nullable NativeForm.Enctype enctype) Sets how the browser encodes the form data when submitting it withNativeForm.Method.POST.voidsetMethod(@Nullable NativeForm.Method method) Sets the HTTP method the browser uses to submit the form.voidsetTarget(@Nullable AnchorTargetValue target) Sets the window, tab or frame that shows the response when the form is submitted.voidsetUnsafeAction(@Nullable String action) Sets the URL the browser submits the form to without validating its scheme.Methods inherited from class com.vaadin.flow.component.HtmlComponent
getTitle, setTitleMethods inherited from class com.vaadin.flow.component.Component
addListener, bindVisible, findAncestor, findAncestor, fireEvent, from, get, getChildren, getElement, getEventBus, getId, getListeners, getLocale, getParent, getTestId, getTranslation, getTranslation, getTranslation, getTranslation, getTranslation, getTranslation, getUI, getUIOrThrow, hasListener, isAttached, isTemplateMapped, isVisible, onAttach, onDetach, onEnabledStateChanged, removeFromParent, scrollIntoView, scrollIntoView, set, setElement, setId, setTestId, setVisible, whenAttachedMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface com.vaadin.flow.component.AttachNotifier
addAttachListenerMethods inherited from interface com.vaadin.flow.component.DetachNotifier
addDetachListenerMethods inherited from interface com.vaadin.flow.component.HasComponents
addMethods inherited from interface com.vaadin.flow.component.HasComponentsOfType
add, addComponentAsFirst, getChildren, getComponentAt, getComponentCount, indexOf, remove, remove, removeAllMethods inherited from interface com.vaadin.flow.component.HasElement
getElementMethods inherited from interface com.vaadin.flow.component.HasEnabled
bindEnabled, isEnabled, setEnabledMethods inherited from interface com.vaadin.flow.component.HasSize
bindHeight, bindWidth, getHeight, getHeightUnit, getMaxHeight, getMaxWidth, getMinHeight, getMinWidth, getWidth, getWidthUnit, setHeight, setHeight, setHeightFull, setMaxHeight, setMaxHeight, setMaxWidth, setMaxWidth, setMinHeight, setMinHeight, setMinWidth, setMinWidth, setSizeFull, setSizeUndefined, setWidth, setWidth, setWidthFullMethods inherited from interface com.vaadin.flow.component.HasStyle
addClassName, addClassNames, bindClassName, bindClassNames, getClassName, getClassNames, getStyle, hasClassName, removeClassName, removeClassNames, setClassName, setClassNameMethods inherited from interface com.vaadin.flow.component.HasText
bindText, getText, getWhiteSpace, setText, setWhiteSpace
-
Constructor Details
-
NativeForm
public NativeForm()Creates a new empty form that is submitted withNativeForm.Method.POST. -
NativeForm
Creates a new form with the given children that is submitted withNativeForm.Method.POST.- Parameters:
components- the children components- Throws:
IllegalArgumentException- if one of the components is aNativeForm
-
-
Method Details
-
setAction
Sets the URL the browser submits the form to. A relative URL is resolved against the<base href>that Vaadin sets to the root of the application, so"login"targets theloginpath of the application, while"/login"ignores its context path.- Parameters:
action- the URL to submit to, ornullto remove the attribute, in which case the browser submits to the URL of the current page- Throws:
IllegalArgumentException- if the URL uses a scheme that is not considered safe, such asjavascript:. The "safeUrlSchemes" configuration is read from the application that this form is attached to, so for a form that isn't attached yet the exception is instead thrown when it is attached. SeesetUnsafeAction(String)for setting a URL that shouldn't be checked at all.
-
setUnsafeAction
Sets the URL the browser submits the form to without validating its scheme.Unlike
setAction(String), this method does not reject URLs based on the "safeUrlSchemes" configuration. Use it only for URLs that are fully under your control and known to be safe. Passing untrusted input here can expose the application to cross-site scripting (XSS) attacks, because ajavascript:action runs when the form is submitted.- Parameters:
action- the URL to submit to, ornullto remove the attribute- See Also:
-
getAction
Gets the URL the browser submits the form to.- Returns:
- the action URL, or
nullif not set - See Also:
-
setMethod
Sets the HTTP method the browser uses to submit the form. A new form usesNativeForm.Method.POST.- Parameters:
method- the method, ornullto remove the attribute, in which case the browser usesNativeForm.Method.GET
-
getMethod
Gets the HTTP method the browser uses to submit the form.- Returns:
- the method, or
nullif not set or not recognized - See Also:
-
setEnctype
Sets how the browser encodes the form data when submitting it withNativeForm.Method.POST.- Parameters:
enctype- the encoding, ornullto remove the attribute, in which case the browser usesNativeForm.Enctype.URLENCODED
-
getEnctype
Gets how the browser encodes the form data when submitting it.- Returns:
- the encoding, or
nullif not set or not recognized - See Also:
-
setTarget
Sets the window, tab or frame that shows the response when the form is submitted. UseAnchorTarget.BLANKto keep the Vaadin UI open while the response opens in a new tab, orAnchorTargetValue.forString(String)with the name of anIFrameto show it there.- Parameters:
target- the target, ornullorAnchorTarget.DEFAULTto remove the attribute, in which case the response replaces the current page
-
getTarget
Gets the window, tab or frame that shows the response when the form is submitted.- Returns:
- the target, or
nullif not set - See Also:
-
add
Adds the given components as children of this component.In case any of the specified components has already been added to another parent, it will be removed from there and added to this one.
- Parameters:
components- the components to add- Throws:
IllegalArgumentException- if one of the components is aNativeForm
-
addComponentAtIndex
Adds the given component as a child of this component at the specific index.In case the specified component has already been added to another parent, it will be removed from there and added to this one.
- Parameters:
index- the index, where the component will be added. The index must be non-negative and may not exceed the children countcomponent- the component to add, value should not be null- Throws:
IllegalArgumentException- if the component is aNativeForm
-
replace
Replaces the component in the container with another one without changing position. This method replaces a component with another one is such a way that the new component overtakes the position of the old component. If the old component is not in the container, the new component is added to the container. If both components are already in the container, their positions are swapped. Component attach and detach events should be taken care as with add and remove.- Parameters:
oldComponent- the old component that will be replaced. Can benull, which will make the newComponent to be added to the layout without replacing any othernewComponent- the new component to be replaced. Can benull, which will make the oldComponent to be removed from the layout without adding any other- Throws:
IllegalArgumentException- if the new component is aNativeForm
-
bindChildren
public <V extends @Nullable Object,S extends Signal<V>> void bindChildren(Signal<List<S>> list, SerializableFunction<S, Component> childFactory) Binds a listSignalto this component using a child component factory. Each itemSignalin the list corresponds to a child component within this component.This component is automatically updated to reflect the structure of the list. Changes to the list, such as additions, removals, or reordering, will update this component's children accordingly.
This component must not contain any children in the default slot (i.e. without a
slotattribute) that are not part of the list. If this component has existing default-slot children when this method is called, or if it contains unrelated default-slot children after the list changes, anIllegalStateExceptionwill be thrown. Named-slot children are allowed and can be added or removed freely while the binding is active.New child components are created using the provided
childFactoryfunction. This function takes aSignalfrom the list and returns a corresponding child component. It shouldn't returnnull. TheSignalcan be further bound to the returned component as needed. Note thatchildFactoryis run inside aEffect, and thereforeSignal.get()calls makes effect re-run automatically on signal value change.Example of usage:
SharedListSignal<String> taskList = new SharedListSignal<>(String.class); UnorderedList component = new UnorderedList(); component.bindChildren(taskList, ListItem::new);
Note: The default implementation adds children directly to the component?s element using the Element API and does not invoke
HasComponentsOfType.add(Component...). Components that overrideaddor manage children indirectly must override this method to provide a suitable implementation or explicitly disable it.A
NativeFormcreated by the factory is rejected with anIllegalArgumentException. While this form is attached, the factory runs in an effect, so the exception is passed to the session error handler instead of being thrown to the caller.
-