You are on page 1of 8

VA A D I N 1 4 R E F E R E N C E C A R D - 1

Vaadin 14 Reference Card


WRITTEN BY ALEJANDRO DUARTE

Introduction <properties>

<maven.compiler.source>1.8</maven.compiler.source>
This reference card is tailored to developers with previous Vaadin <maven.compiler.target>1.8</maven.compiler.target>
experience. It is a quick reference on key concepts and everyday tasks <failOnMissingWebXml>false</failOnMissingWebXml>
that arise while using the framework. For a comprehensive reference or </properties>
tutorials to learn Vaadin, see the links in the Useful links section. <dependencies>

<dependency>

<groupId>com.vaadin</groupId>

<artifactId>vaadin-core</artifactId>
Useful links <version>14.2.0</version>

</dependency>
Learn: https://vaadin.com/docs
</dependencies>
Follow tutorials: https://vaadin.com/tutorials
</project>
Create new projects: https://vaadin.com/start
Edit a theme: https://demo.vaadin.com/lumo-editor
Search Vaadin Icons: https://vaadin.com/components/vaadin-icons/
MainView.java:
html-examples
Search UI components: https://vaadin.com/components import com.vaadin.flow.component.Text;

Find Add-ons: https://vaadin.com/directory import com.vaadin.flow.component.orderedlayout.VerticalLayout;

Ask questions: https://vaadin.com/forum import com.vaadin.flow.router.Route;

Report issues: https://github.com/vaadin/flow/issues @Route(“demo”) // localhost:8080/demo

public class MainView extends VerticalLayout {

public MainView() {

add(new Text(“It works!”));

Minimal application using Maven }

}
pom.xml:

<?xml version=”1.0” encoding=”UTF-8”?>

<project xmlns=”http://maven.apache.org/POM/4.0.0”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.

apache.org/xsd/maven-4.0.0.xsd”>

<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>

<artifactId>demo</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>war</packaging>
VA A D I N 1 4 R E F E R E N C E C A R D - 2

UI Components HasAutocorrect Enables use of the setAutocorrect


isAutocorrect
autocorrect attribute.

All UI components are instances of Component.


HasComponents Adds and removes child add

components (extends remove

HasElements and HasEnabled). removeAll

HasDataProvider Enables data providers. setDataProvider


setItems

HasElement Retrieves underlying getElement

element.
HasEnabled Enables or disables setEnabled

components (extends isEnabled

HasElement).

HasOrderedComponents Enables component replace

ordering (extends indexOf

HasComponents). getComponentCount
Input getComponentAt

HasPrefixAndSuffix Enables prefix and setPrefixComponent


CheckBox, ComboBox, DatePicker, Grid, TextField, TextArea,
suffix slots for inserting getPrefixComponent
TimePicker, PasswordField, RadioButtonGroup, Upload, Custom- components. setSufixComponent

Field, EmailField, NumberField, RadioButton, Select, Inte- getSufixComponent

gerField, BigDecimalField, CheckBoxGroup, MultiSelectList- HasSize Enables component sizing. setWidth


getWidth
Box, DateTimePicker.
setHeight
getHeight
setSizeFull
Visualization and interaction setSizeUndefined

Accordion, Button, ContextMenu, Details, Dialog, Grid, Icon, HasStyle Enables CSS styles and CSS addClassName

class names. removeClassName


Item, MenuBar, Notification, ProgressBar, Tabs, TreeGrid.
setClassName
getClassName
hasClassName
HTML
addClassNames

Div, Span, Section, Header, Footer, Article, H1, H2, H3, removeClassNames
getStyle
H4, H5, H6, Paragraph, Label, Anchor, OrderedList, ListItem,
HasText Enables text content. setText
Image, DescriptionList, Emphasis, Hr, IFrame, Input, Main,
getText
NativeButton, Nav, Pre, Section, UnorderedList.
HasTheme Enables theming. addThemeName
removeThemeName
setThemeName
Layouts
getThemeName

FlexLayout, HorizontalLayout, Scroller, VerticalLayout, getThemeNames


setThemeName
SplitLayout, AppLayout, FormLayout, Login.
hasThemeName
addThemeNames
removeThemeNames
Mixin interfaces
HasValidation Enables input validation. setErrorMessage
UI components implement mixin interfaces with default methods to getErrorMessage
setInvalid
build up the functionality of the component. For example, CheckBox im-
isInvalid
plements the HasSize, HasStyle, Focusable, ClickNotifier, and
HasValue Enables user-editable setValue
HasValueAndElement interfaces. getValue
values.
addValueChangeListener
getEmptyValue
getOptionalValue
Interface Purpose Methods
isEmpty
clear
BlurNotifier Handles blur events. addBlurListener
setReadOnly
isReadOnly
ClickNotifier Handles click events. addClickListener setRequiredIndicatorVisible
isRequiredIndicatorVisible

CompositionNotifier Handles DOM Composition addCompositionStartListener HasValueAndElement See extended interfaces.


Extends HasValue,
events (text input). addCompositionUpdateListener
HasElement, and HasEnabled.
addCompositionEndListener

Focusable Focus, blur, and set tab setTabIndex

order (extends HasElement, getTabIndex


InputNotifier Handles input events. addInputListener
BlurNotifier, FocusNotifier, focus

and HasEnabled). blur


KeyNotifier Handles keyboard events. addKeyDownListener
FocusNotifier Handles focus events. addFocusListener
addKeyPressListener
addKeyUpListener
HasAutocapitalize Enables use of the setAutocapitalize
PollNotifier Handles events for addPollListener
autocapitalize attribute. getAutocapitalize
asynchronous UI updates.

HasAutocomplete Enables use of the setAutocomplete


SortNotifier Handles sort events. addSortListener
autocomplete attribute. getAutocomplete
VA A D I N 1 4 R E F E R E N C E C A R D - 3

Sizing setFlexDirection(FlexDirection) Sets the direction in which the


components are layed out (as
VerticalLayout, HorizontalLayout, FlexLayout a column or a row) with the
possibility to reverse the order.
setWidth(String) Sets the component size in units (px, pt, pc, cm, mm, in, See the FlexDirection enum
setHeight(String) em, or rem) or percentage (%) relative to the available values.
area in the containing layout. null or -1 means an
setFlexWrap(FlexWrap) Sets how the contained
undefined size (see below).
components behave when they
setSizeFull() Sets both dimensions to 100% relative size. don’t fit inside the layout. See the
FlexWrap enum values.
setHeightFull() Sets the corresponding dimension to 100% relative size.
setWidthFull()

setSizeUndefined() Sets both dimensions as undefined, causing the


component to shrink to its minimum size.
setMinWidth(String) Sets the minimum size of the component in units.
setMinHeight(String)

setMaxWidth(String) Sets the maximum size of the component in units.


setMaxHeight(String)

expand(Component...) Sets the flex grow property to 1 for the specified


components.
setFlexGrow(double) Specifies the proportion of the available space a
component takes.

VerticalLayout, HorizontalLayout

setBoxSizing(BoxSizing) Sets how the total width and height of a component is


calculated. See the BoxSizing enum values.

FlexLayout

setFlexShrink(double, Sets how components shrink relative to the other


HasElement...) components in the layout.
setFlexBasis(String, Sets the initial main size of a component. Alignment on the primary axis
HasElement...)

Alignment
VerticalLayout, HorizontalLayout, FlexLayout

setAlignItems(Alignment) Aligns the contained


components. Default: STRETCH
setAlignSelf(Alignment, HasElement...) Same as
setHorizontalComponentAlignment
or setVerticalComponentAlignment.
setJustifyContentMode(JustifyContentMode) Sets how the extra space inside
the layout is distributed among
the components. Equivalent to
the justify-content CSS property.

VerticalLayout, HorizontalLayout

setDefaultHorizontalComponentAlignment(Alignment) Changes the default


alignment of the contained
components.
setHorizontalComponentAlignment(Alignment, Aligns the contained
Component...) components in the “other”
setVerticalComponentAlignment(Alignment, axis of the layout (for
Component...) example, horizontally in a
VerticalLayout)

FlexLayout
setAlignContent(ContentAlignment) Sets how the “lines” within
the layout are aligned when
there is extra space. See the
ContentAlignment enum values.
VA A D I N 1 4 R E F E R E N C E C A R D - 4

Alignment on the secondary axis Navigation

TIP: Register views at runtime in a ServiceInitListener implemen-


tation:

RouteConfiguration.forSessionScope().setRoute(“view”,View.class);

Parameters

@Route(“”)

public class GreetingView extends VerticalLayout

implements HasUrlParameter<String> {

@Override

public void setParameter(BeforeEvent event,

String parameter) {

String name = event.getLocation()

.getQueryParameters()

.getParameters()

.get(“name”)

.get(0);

add(new Span(parameter + “, “ + name));

AppLayout

TIP: Use @OptionalParameter and @WildcardParameter when


needed.

setPrimarySection(Section) Defines whether the navbar or the drawer display


first.

setDrawerOpened(boolean) Shows or hides the drawer section.


VA A D I N 1 4 R E F E R E N C E C A R D - 5

Navigation lifecycle Binding

Two-way data binding. Sets the bean values in the input fields and sets
values in the bean when the input fields values change:
Interface Description
binder.setBean(person);
BeforeLeaveObserver Allows delaying or canceling the navigation, or
BeforeLeaveListener changing the navigation to a different destination.
One-way data binding. Sets values from the bean to the input fields:
Reroute with the BeforeLeaveEvent::reroute() methods.
Reroute and update the browser URL with the binder.readBean(bean);
BeforeLeaveEvent::forward() methods.

BeforeEnterObserver* Allows changing the navigation to a different One-way data binding. Sets values from the input fields to the bean:
BeforeEnterListener destination. binder.writeBean(bean);
Reroute with the BeforeEnterEvent::reroute() methods.
Reroute and update the browser URL with the
BeforeEnterEvent::forward() methods.
Gets the bean:

AfterNavigationObserver
Person person = binder.getBean();
Allows updating parts of the UI once the navigation
AfterNavigationListener has been completed.

Advanced usage
* Needs to be defined in a UI init listener if you want it to run before any
binder.forField(ageTextField)
views are created, for instance for general access control.
.asRequired(“Is required”)

NOTE: You cannot navigate from a constructor. Use .withNullRepresentation(“”)

BeforeEnterListener and reroute accordingly. .withConverter(new StringToIntegerConverter(

“Must be an integer”))

.withValidator(age -> age > 0,

“Must be a positive integer”)

Forms and data binding .withStatusLabel(ageStatus)

.bind(p -> p.getAge(), (p, age) -> p.setAge(age));


Binder is a helper class to set values in Java beans from input fields and try {
vice versa. binder.writeBean(person);

...
new Binder<>(Person.class); // property names supported } catch (ValidationException e) {
new Binder<>(); // property names not supported ...

Java Bean Validation


NOTE: If you used setBean earlier, use
BeanValidationBinder<Person> binder = new
if(movieBinder.validate().isOk()){...}
BeanValidationBinder<>(Person.class);

if (binder.validate().isOk()) {
TIP: Use the writeBeanAsDraft(BEAN) and writeBeanIfVal-
...
id(BEAN) methods when needed.
}

Requires Java Bean Validation in the classpath


Bind by field name

Basic configuration

binder.bind(textField, Person::getName, Person::setName);

Or:

binder.bind(

textField,

person -> person.getName(),

(person, name) -> person.setName(name)

);

TIP: Use @Id when possible to improve maintainability.


VA A D I N 1 4 R E F E R E N C E C A R D - 6

Sessions, Views, and UIs Application lifecycle


TIP: Reuse view instances using @PreserveOnRefresh. A new UI Servlet customization
instance is created after a browser refresh.
public class CustomServlet extends VaadinServlet {

@Override
Using the Vaadin Session protected void servletInitialized() throws ServletException {

super.servletInitialized();

...your logic here...

Register the servlet using @WebServlet or in the web.xml file.

Once per VaadinService instance

public class AppServiceInitListener

implements VaadinServiceInitListener {

@Override

public void serviceInit(ServiceInitEvent event) {

event.addBootstrapListener(response -> {

...change the bootstrap page...

VaadinSession.getCurrent() });

event.addDependencyFilter((dependencies, filterContext) -> {


setAttribute(String, Object) Stores an object by name. ...add/remove/change client-side dependencies...
setAttribute(Class<T>, T) Stores an object by type. return dependencies;
getAttribute(String) Gets a stored object by name. });

getAttribute(Class<T>) Gets a stored object by type. event.addRequestHandler((session, request, response) -> {

close() ...change how responses are handled...


Flags the session for discarding (doesn’t destroy
the HTTP session). return false;

});

TIP: Invalidate the HTTP session with VaadinSession.getCurrent(). }

getSession().invalidate(); }

Requires the following file:

With the following content:


com.company.AppServiceInitListener

Session destroy listeners

public class ApplicationServiceInitListener

implements VaadinServiceInitListener {

@Override

public void serviceInit(ServiceInitEvent initEvent) {

initEvent.getSource().addSessionDestroyListener(

sessionEvent -> {

... your logic here ...

});

}
VA A D I N 1 4 R E F E R E N C E C A R D - 7

UI component attach/detach Styling


Use these methods to free resources and clean up: Dark Theme
public class CustomComponentOrView extends VerticalLayout { @Theme(value = Lumo.class, variant = Lumo.DARK)
@Override public class MainView extends ... { }
protected void onAttach(AttachEvent attachEvent) {
Custom CSS
...custom logic when the component is attached to the UI ...

} CSS (PROJECT_ROOT/frontend/css-file.css):

@Override .css-class-name {
protected void onDetach(DetachEvent detachEvent) { ... custom css rules ...
...custom logic when the component is detached from the }
UI...

}
Java (View.java):

} ...

@CssImport(“./styles/css-file.css”)

public class MainView extends ... {


TIP: Use addAttachListener(ComponentEventListener<Attach public MainView() {
Event>) and addDetachListener(ComponentEventListener< ...
DetachEvent>)to clean up conditionally. Button button = new Button();

button.addClassName(“css-class-name”);

Heartbeat }

}
The objective of the heartbeat mechanism is to remove UI instances that
are no longer active in the same session.

The client side sends keep-alive heartbeat requests at a configurable Shadow DOM
rate. A UI expires if three consecutive heartbeats are missed. Vaadin components are web components in the client side. The cli-
ent-side implementation is encapsulated inside the Shadow DOM.
NOTE: The HTTP session doesn’t expire if there is a browser window
open. This is a side effect of the heartbeats. Use the closeIdleSes- Java:
sions configuration parameter to override this behavior.
@CssImport(value = “./styles/styles.css”, themeFor = “vaadin-

button”)

public class MainView extends VerticalLayout { ... }

Static content
NOTE: Only works for web components that implement vaadin-the-
Templates, CSS, Javascript, images:
mable-mixin.

WAR src/main/webapp/frontend/
CSS (styles.css):
JAR src/main/resources/META-INF/resources/frontend/

[part=”label”] {
Favicon:
… custom CSS ...

}
WAR src/main/webapp/icons/icon.png

JAR src/main/resources/META-INF/resources/icons/icon.png

TIP: Use the browser inspector to see the available parts of a web
NOTE: These resources are not bundled. component

TIP: Use the PageConfigurator interface to customize the name and


location of the favicon.
VA A D I N 1 4 R E F E R E N C E C A R D - 8

Responsive design Configuration properties


Components such as AppLayout and FormLayout include responsive
productionMode Switches application to production mode.
features. Use CSS media queries to fully customize layouts.
requestTiming Whether request timing info is available. This can
be used for performance testing.
@media only screen and (min-width: 1024px) {
disable-xsrf-protection Enables or disables cross-site request-forgery
html {
protection.
… custom CSS ...
heartbeatInterval The interval in seconds between UI heartbeat
}
requests, or a negative number if heartbeats are
} disabled.
closeIdleSessions Whether a session should be closed when all
its open UIs have been idle for longer than its

Production builds configured maximum inactivity time.


pushMode Options: disabled or manual.
Performed with the vaadin-maven-plugin and the prepare-frontend pushURL URL used for push requests.
and build-frontend goals. Projects created with the Maven archetype
syncIdCheck Enables or disables id checking. The sync id is
or on the Vaadin web site can activate a production build with mvn
used to gracefully handle situations when the
package -Pproduction. client sends a message to a connector that has
recently been removed on the server.

NOTE: A production build is necessary to deploy to external servers. sendUrlsAsParameters Enables or disables sending of URLs as GET and
POST parameters in requests with content type
application/x-www-form-urlencoded.
Maven profile (all Vaadin starters include this profile):
pushLongPollingSuspendTimeout Long poll push strategy timeout in milliseconds
<profile>
maxMessageSuspendTimeout Maximum time in milliseconds that the client will
<id>production</id> wait for the predecessors of a received out-of-
<properties> order message.

<vaadin.productionMode>true</vaadin.productionMode> load.es5.adapters Includes polyfills for browsers that don’t support


</properties> ES6.

<dependencies> frontend.url.es5 Location of the web component’s files for


<dependency> browsers that don’t support ES6.
frontend.url.es6 Location of the web component’s files for
<groupId>com.vaadin</groupId>
browsers that support ES6.
<artifactId>flow-server-production-mode</artifactId>
disable.webjars Enables or disables WebJars.
</dependency>
original.frontend.resources Whether to use bundled fragments.
</dependencies>

<build> i18n.provider I18NProvider implementation.


<plugins> disable.automatic.servlet. Whether the framework should register
<plugin> registration automatic servlets for the application.
<groupId>com.vaadin</groupId> compatibilityMode Enables Vaadin 13 compatibility mode.
<artifactId>vaadin-maven-plugin</artifactId> devmode.optimizeBundle Enables or disables bytecode scanning in dev
<executions> mode. If enabled, entry points are scanned for
<execution> reachable frontend resources. If disabled, all
classes on the classpath are scanned.
<goals>
pnpm.enable Whether to use pnpm instead of npm for
<goal>build-frontend</goal>
resolving and downloading of frontend
</goals> dependencies.
<phase>compile</phase>

</execution>

</executions>

</plugin>

</plugins>

</build>

</profile>

A production build reduces the bundle size in several ways:

• Debugging information (main source maps) not included.


• The JS implementation is included only for components that are
used (Java classes are analyzed).
• The script content is minified.
• The client-side bundle is gzipped.

You might also like