You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. ---
  2. title: Vaadin Tutorial
  3. order: 1
  4. layout: page
  5. subnav_auto_list_numbers: true
  6. subnav:
  7. - title: Overview
  8. href: '#framework.tutorial.overview'
  9. subnav:
  10. - title: Installing the Development Tools
  11. href: '#framework.tutorial.overview.tools'
  12. - title: Creating a project using an archetype
  13. href: '#framework.tutorial.archetype'
  14. - title: Adding a demo "backend"
  15. href: '#framework.tutorial.backend'
  16. - title: Listing entities in a Grid
  17. href: '#framework.tutorial.grid'
  18. - title: Creating live filtering for entities
  19. href: '#framework.tutorial.filtering'
  20. - title: Creating a form to edit Customer objects
  21. href: '#framework.tutorial.form'
  22. subnav:
  23. - title: Creating a form using Vaadin Designer
  24. href: '#framework.tutorial.form.designer'
  25. subnav:
  26. - title: Installing Vaadin Designer
  27. href: '#framework.tutorial.form.designer.install'
  28. - title: Creating the form design
  29. href: '#framework.tutorial.form.designer.create'
  30. - title: Creating a form using plain Java
  31. href: '#framework.tutorial.form.java'
  32. - title: Connecting the form to the application
  33. href: '#framework.tutorial.form-connection'
  34. - title: It works! What next?
  35. href: '#framework.tutorial.next'
  36. ---
  37. :sectnums:
  38. [[framework.tutorial]]
  39. = Vaadin Tutorial
  40. This tutorial gives you an overview of how you can use https://vaadin.com/framework[Vaadin Framework] to build single-page web UIs for your Java application.
  41. All you need to start with it is JDK 8 and an https://en.wikipedia.org/wiki/Integrated_development_environment[IDE], such as Eclipse.
  42. While this tutorial is written for Eclipse users, you can use your IDE of choice.
  43. No extensive knowledge of Java is needed, only basic programming skills are required.
  44. [[framework.tutorial.overview]]
  45. == Overview
  46. You'll have your first Vaadin app running in your IDE in a couple of minutes. To complete the whole tutorial, you'll need about 20 to 60 minutes, depending on your existing experience.
  47. Naturally, you can just do the beginning of the exercise or pick any of the steps you want.
  48. To start from a specific step, we have prepared the example code after each step to be downloaded as a zip file.
  49. In this tutorial, we build a simple customer management system.
  50. It is not a real application; we use an in-memory "back-end", so that you can understand how to hook it to an existing Java based back-end.
  51. We cover the basic Vaadin development and you can use the result as a basis for more experiments with Vaadin, such as using add-ons, your own custom look-and- feel (aka. theme), adding new views, or optimizing the result for mobile support.
  52. [[figure.framework.tutorial.final-ui]]
  53. .UI to be built in the tutorial
  54. image::img/finalUI.jpg[]
  55. If you do not want to do the exercise at all, you can also just https://github.com/vaadin/tutorial/[download the final application] and play around with it.
  56. TIP: In addition to this written tutorial, we have recorded the steps as https://www.youtube.com/playlist?list=PLcRrh9hGNalkZx921iMqZ-jXR0C72eIPR[a series of videos]. You can just watch all the videos or watch the video of each step before you do the same step yourself.
  57. [[framework.tutorial.overview.tools]]
  58. === Installing the Development Tools
  59. The tutorial uses Java 8, so please ensure that you have an up-to-date JDK 8 installed.
  60. Most Linux distributions can use package managers to install JDK8.
  61. Windows and Mac users should download it from http://www.oracle.com/technetwork/java/javase/downloads/index.html[Oracle's Java
  62. SE site].
  63. Also make sure you have the latest version of your IDE.
  64. Eclipse is available in various packages; be sure to download the *Eclipse IDE for Java EE Developers* from http://www.eclipse.org/downloads/[eclipse.org].
  65. [[framework.tutorial.archetype]]
  66. == Creating a Project from an Archetype
  67. The following video shows how to do this step of the tutorial:
  68. video::sMGHSK_97NI[youtube, width="640", height="400"]
  69. As the starting point for the application, we use a Maven archetype called `vaadin-archetype-application`.
  70. Archetypes are project stubs that have some example code and a basic Maven build script.
  71. . Start by choosing "File > New > Maven Project" from the menu.
  72. +
  73. [[figure.framework.tutorial.create-maven-project]]
  74. .Create a new Maven project
  75. image::img/createMavenProject.jpg[width=70%]
  76. +
  77. TIP: If the [guilabel]#Maven Project# is not visible in the menu, you should switch to the _Java EE_ perspective.
  78. You can use the shortcut button in the tool bar or "Window > Perspective" to switch to the perspective.
  79. . The first step in the wizard is good as is for our purpose.
  80. Just click [guibutton]#Next#.
  81. . In the second step, you need to choose the `vaadin-archetype-application` archetype.
  82. +
  83. .Selecting the archetype
  84. image::img/projectWizard2-top.jpg[width=70%]
  85. +
  86. You can first try to find it using the filtering function.
  87. +
  88. If Eclipse has not yet indexed the archetype catalog, you need to manually add the archetype details.
  89. +
  90. TIP: Some Eclipse installations do not automatically add Maven Central to the list of Maven catalogues, resulting in the Vaadin archetypes not being available in the wizard. To fix this, open Eclipse Preferences > Maven > Archetypes and select `Add Remote Catalog`. The URL to the Maven Central catalog file is `http://repo1.maven.org/maven2/archetype-catalog.xml`. After applying the changes, the Vaadin archetypes should be available in the wizard.
  91. +
  92. // +
  93. // .Adding a new archetype
  94. // image::img/projectWizard2-add.jpg[width=70%]
  95. +
  96. Click the [guibutton]#Add Archetype# button.
  97. +
  98. .Settings for a new archetype
  99. image::img/projectWizardAddArchetype-crop.jpg[width=70%]
  100. +
  101. Enter the following values:
  102. +
  103. [guilabel]#Group ID#::
  104. Give `com.vaadin`
  105. [guilabel]#Artifact ID#::
  106. Give `vaadin-archetype-application`
  107. [guilabel]#Version#::
  108. You can find the latest Vaadin version number from https://vaadin.com/framework/releases[vaadin.com/framework/releases].
  109. [guilabel]#Repository URL#::
  110. This can be left blank.
  111. +
  112. And click [guibutton]#OK#.
  113. Now you can select the new archetype from the list.
  114. +
  115. WARNING: Eclipse has a bug in its project wizard.
  116. The `vaadin-archetype-application` may not appear in the listing, even though you added it using the [guibutton]#Add Archetype# button.
  117. If this occurs, close the whole new project wizard and re-open it by selecting "File > New > Maven Project" again.
  118. The archetype then typically appears in the listing and can be found by the filtering functionality.
  119. . In the next wizard step, type in the following fields:
  120. [guilabel]#Group Id#:: `my.vaadin`
  121. [guilabel]#Artifact Id#:: `app`
  122. +
  123. and click [guibutton]#Finish#.
  124. If this is your first Vaadin app, creating a project might take a while, depending on the speed of your network, as Vaadin libraries and other dependencies are being downloaded.
  125. Maven caches them on your local file system.
  126. Creating your next Maven-based Vaadin project will be much faster.
  127. Right click on the newly created project and choose "Run as > Maven Install".
  128. This initiates a full build of your application and finally creates a https://en.wikipedia.org/wiki/WAR_(file_format)[WAR] file into the [filename]#target# directory.
  129. You can deploy the WAR file to your application server.
  130. The first build might take a while, as Maven might again need to download some new modules.
  131. TIP: For the Maven compilation to work you need a JDK to be configured in your
  132. Eclipse in "Window > Preferences > Java > Installed JREs > Add...".
  133. This step is necessary at least on Windows, if you are using a fresh installation of Eclipse or for some other reason haven't configured a JDK to your Eclipse.
  134. The JDK by default installs to [filename]#\Program Files\Java# on Windows.
  135. You can make JDK the default JRE for your Eclipse.
  136. While the build is running, let us have a look at what the archetype created for
  137. you.
  138. You can browse your project resources from the tree structure in the [guilabel]#Project Explorer#.
  139. Maven's [filename]#pom.xml# on top level contains settings for building your project and declares the used dependencies.
  140. Open [guilabel]#Java Resources# and below it [filename]#src/main/java#, the main source directory, and [packagename]#my.vaadin.app#, the main Java package that will contain your Vaadin UI code.
  141. TIP: Eclipse shows all project files in the Project Explorer.
  142. In this case, you can also find your [filename]#.java# files from under the top-level [filename]#src# node.
  143. However, the suggested method is to access them from under the [guilabel]#Java Resources# node, which is optimized for editing Java source code.
  144. The UI code (and the Servlet declaration) used by the application stub can be
  145. found in the [filename]#MyUI.java# file.
  146. Let us read it through to see how it works.
  147. The [methodname]#init()# method of a UI class is triggered when a user enters your web application.
  148. The [classname]#VerticalLayout# is one of the most used layout components, which
  149. are used to position and display other Vaadin components in your UI classes.
  150. The example code creates one [classname]#TextField# to allow the user to input her name and a [classname]#Button# whose click listener dynamically adds a new [classname]#Label# component to the main layout.
  151. In the end of the [methodname]#init()# method, we just configure the main layout and place components into it and set it to be the content of [classname]#MyUI#.
  152. To test your first Vaadin application, right-click on the project and choose "Debug as > Maven build...".
  153. The debug mode is slightly slower than the basic run mode, but it often helps you to figure out what is happening in your application.
  154. [[figure.framework.tutorial.debug-as-maven-build]]
  155. .Starting the server using a Maven target
  156. image::img/debugAsMavenBuild.jpg[]
  157. In the dialog, type `Run in jetty` to the [guilabel]#Name# input and `jetty:run` to the [guilabel]#Goals# input.
  158. [[figure.framework.tutorial.jetty-run]]
  159. .Generating a Maven launch for `jetty:run` target
  160. image::img/debugAsMavenBuild2.jpg[]
  161. Before clicking debug, to make sure debugging works properly, add your Java
  162. project to the source lookup path from the [guilabel]#Source# tab, as it is being done in <<figure.tutorial.creating.add-sources>>.
  163. [[figure.tutorial.creating.add-sources]]
  164. .Adding sources for debugging
  165. image::img/debugAsMavenBuildAddSources.jpg[]
  166. Now click [guibutton]#Debug# to continue.
  167. This will download a small Java web server (if not cached to your local Maven repository), and use it to host your application.
  168. Once the server has started, point your browser to the URL http://localhost:8080/[http://localhost:8080/] to see the running application.
  169. If you make changes to the code, the Jetty server will notice the changes and in
  170. a couple of seconds most changes are automatically deployed.
  171. Reloading the page in your browser will show the changes.
  172. TIP: In some cases your JVM might not allow injecting changes on the fly.
  173. In these cases, Eclipse will complain about "Hot code replacement error".
  174. Just choose to restart the server to get the latest changes.
  175. Many Java developers use a commercial tool called http://zeroturnaround.com/software/jrebel/[JRebel] to make code replacement work better.
  176. Mastering the usage of the Java debugger is also handy to better understand how your application actually works and fixing bugs that all developers write at some point.
  177. As Vaadin is "only" Java code, you can use all of Java's debugging tools, which cannot be done with other UI frameworks where the UI is written (partly) in HTML and/or JavaScript.
  178. Double-click on the line number in the Java editor, for example of the following line in the click listener:
  179. [source,java]
  180. ----
  181. layout.addComponent(new Label("Thanks " + name.getValue()));
  182. ----
  183. Doing so adds a breakpoint to the selected line.
  184. If you then click the button in your browser, the execution of the application will stop on that line.
  185. Eclipse will ask you to enter to _Debugging perspective_.
  186. That way you can step through the execution and inspect the variables.
  187. Clicking on the _play_ icon in the toolbar will continue the execution.
  188. Double-click the same line again to remove the breakpoint.
  189. [[figure.framework.tutorial.breakpoint]]
  190. .Execution in a break point in the button click listener
  191. image::img/debugInBreakPointVariable.jpg[]
  192. Clicking the red square in the [guilabel]#Console# view will terminate the server process.
  193. You can restart it easily form the run/debug history.
  194. You can find that from the small down arrow next to the green play button or bug button (for the debug mode) in the tool bar.
  195. Alternatively, you can use the main menu "Run > Run
  196. history/Debug history > Run in Jetty".
  197. To get back to the _Java EE Perspective_, an Eclipse mode designed for editing Java web app code, click the [guibutton]#Java EE# button in the toolbar.
  198. [[framework.tutorial.backend]]
  199. == Adding a demo "backend"
  200. TIP: Starting from this step directly? https://github.com/vaadin/tutorial/archive/v8-step2.zip[Download the project] for this step, extract the zip file and choose "Import... > Maven > Existing Maven project".
  201. Before getting more into real Vaadin development, let us introduce some domain objects and a "fake backend".
  202. In a real-world application, you will most likely have something similar, implemented with, for example, JPA and EJB or a Spring-based service.
  203. The following video shows how to do this step of the tutorial:
  204. video::qF31jkBFbR0[youtube, width="640", height="400"]
  205. Copy the following three classes from github to your project.
  206. Class names point to the classes hosted in Github.
  207. Copying classes can be done in many ways.
  208. TIP: The fastest way to copy classes using Eclipse is to use your good old
  209. clipboard. Select the text content of the whole class from your browser, choose
  210. "Edit > Copy", focus the node representing the [packagename]#my.vaadin.app# Java package in Eclipse's Java Resources view and choose "Edit > Paste".
  211. Eclipse is smart enough to automatically create a properly named Java file for the class.
  212. * https://raw.githubusercontent.com/vaadin/tutorial/master/src/main/java/my/vaadin/app/CustomerStatus.java[CustomerStatus] - this is a simple enum class
  213. * https://raw.githubusercontent.com/vaadin/tutorial/master/src/main/java/my/vaadin/app/Customer.java[Customer] - this is the main domain object, a basic Java bean that we will be using in our example
  214. * https://raw.githubusercontent.com/vaadin/tutorial/master/src/main/java/my/vaadin/app/CustomerService.java[CustomerService] - this is a simple facade via which you can request and modify [classname]#Customer# instances.
  215. You can think of this as your entry point to your fake database.
  216. In the next steps, we will be using these classes and build a UI around them.
  217. The actual implementation of these classes is not relevant for this tutorial, but feel free to have a look around.
  218. [[framework.tutorial.grid]]
  219. == Listing entities in a Grid
  220. TIP: Starting from this step directly? https://github.com/vaadin/tutorial/archive/v8-step3.zip[Download the project] for this step, extract the zip file and choose "Import... > Maven > Existing Maven project".
  221. Often when you start building a UI for a data-centric application, the first
  222. thing you want to do is to list your data from your back-end.
  223. There are several components and ways in Vaadin to do this.
  224. In this example, we will use the Grid component for tabular presentation of our customers.
  225. The following video shows how to do this step of the tutorial:
  226. video::EBCm-Vf_fUs[youtube, width="640", height="400"]
  227. We start by introducing a [classname]#Grid# to the [classname]#MyUI# class.
  228. We could of course just introduce the Grid as a variable in the [methodname]#init()# method, but we most likely want to refer to it later.
  229. Also, let us get a reference to the [classname]#CustomerService#.
  230. [source,java]
  231. ----
  232. public class MyUI extends UI {
  233. // Add the next two lines:
  234. private CustomerService service = CustomerService.getInstance();
  235. private Grid<Customer> grid = new Grid<>(Customer.class);
  236. // The rest is already there...
  237. @Override
  238. protected void init(VaadinRequest vaadinRequest) {
  239. ...
  240. ----
  241. TIP: If you are new to Java development, you probably do not feel comfortable
  242. with the red compilation error for the line where the [classname]#Grid# got introduced, because of a missing import.
  243. This is easily fixed in Eclipse by using the
  244. menu:Source[Organize Imports] command. Learn its shortcut (kbd:[Ctrl-Shift-O] or
  245. kbd:[CMD-Shift-O] on Macs), you'll be using it a lot in Java development. In
  246. possible class name collisions, always choose the appropriate class from the
  247. _com.vaadin.ui_ package if you want to import core Vaadin UI classes like the
  248. Grid.
  249. To simply list all properties of all Customer objects from the backend service,
  250. replace the init method with the following snippet:
  251. [source,java]
  252. ----
  253. @Override
  254. protected void init(VaadinRequest vaadinRequest) {
  255. final VerticalLayout layout = new VerticalLayout();
  256. // add Grid to the layout
  257. layout.addComponents(grid);
  258. // fetch list of Customers from service and assign it to Grid
  259. List<Customer> customers = service.findAll();
  260. grid.setItems(customers);
  261. setContent(layout);
  262. }
  263. ----
  264. TIP: Again, use the organize imports feature. The List object we use here is
  265. _java.util.List_.
  266. As we'll want to refresh the listing from various places in our application,
  267. extract the customer listing part into its own "updateList" method with the
  268. *public* modifier. The public modifier is handy later when we want to update the
  269. listing from other classes. You can let Eclipse help here by selecting the
  270. relevant lines and using the "quick fix" feature (kbd:[Ctrl+1] or kbd:[Cmd+1] on
  271. Macs). The extracted method call looks like this:
  272. [source,java]
  273. ----
  274. public void updateList() {
  275. List<Customer> customers = service.findAll();
  276. grid.setItems(customers);
  277. }
  278. ----
  279. If you try the application now, you'll see an empty Grid with no columns. To add columns, configure
  280. the Grid using the _setColumns_ method to show the "firstName", "lastName" and
  281. "email" properties.
  282. [source,java]
  283. ----
  284. grid.setColumns("firstName", "lastName", "email");
  285. ----
  286. At this point the body of the MyUI class should look like this (servlet declaration
  287. omitted):
  288. [source,java]
  289. ----
  290. private CustomerService service = CustomerService.getInstance();
  291. private Grid<Customer> grid = new Grid<>(Customer.class);
  292. @Override
  293. protected void init(VaadinRequest vaadinRequest) {
  294. final VerticalLayout layout = new VerticalLayout();
  295. grid.setColumns("firstName", "lastName", "email");
  296. // add Grid to the layout
  297. layout.addComponent(grid);
  298. updateList();
  299. setContent(layout);
  300. }
  301. public void updateList() {
  302. // fetch list of Customers from service and assign it to Grid
  303. List<Customer> customers = service.findAll();
  304. grid.setItems(customers);
  305. }
  306. ----
  307. You can now save your changes to the file and verify the changes from your browser.
  308. You can do this at any point during the rest of the tutorial as well.
  309. [[framework.tutorial.filtering]]
  310. == Creating live filtering for entities
  311. TIP: Starting from this step directly? https://github.com/vaadin/tutorial/archive/v8-step4.zip[Download the project] for this step, extract the zip file and choose menu:Import...[Maven>Existing Maven project].
  312. A search functionality is expected in every modern application and it is
  313. also a nice Vaadin development exercise. Let's add a filtering functionality to
  314. the Customer listing we created in the previous step.
  315. The following video shows how to do this step of the tutorial:
  316. video::kyMaJLUtz3g[youtube, width="640", height="400"]
  317. We'll start by introducing a [classname]#TextField# component as a field to our [classname]#UI# class:
  318. [source,java]
  319. ----
  320. private TextField filterText = new TextField();
  321. ----
  322. In the [methodname]#init()# method, configure the text field to contain a helpful input prompt
  323. and add a text change listener to the field. The exact place of these lines is
  324. not important, but add them, for example, after you have introduced the _layout_
  325. object.
  326. [source,java]
  327. ----
  328. filterText.setPlaceholder("filter by name...");
  329. filterText.addValueChangeListener(e -> updateList());
  330. filterText.setValueChangeMode(ValueChangeMode.LAZY);
  331. ----
  332. TIP: To keep your code more readable, you can use autoformat after you write or
  333. copy paste code snippets. The default keyboard shortcut in Eclipse is
  334. kbd:[Ctrl+Shift+F] or kbd:[Cmd+Shift+F]
  335. As its name implies, the value change listener allows you to react to changes in
  336. the value contained in the text field. It is configured so that the event is fired
  337. lazily while the user is typing, when there is a small pause in the typing.
  338. This makes it perfect for this kind of automatic filtering. When the
  339. user has changed the text, we'll just update the listing calling the _updateList_
  340. method.
  341. To keep the _updateList_ method functional, it should take into consideration
  342. the possible value in the filterText field. Change the line for fetching the
  343. customers into this:
  344. [source,java]
  345. ----
  346. List<Customer> customers = service.findAll(filterText.getValue());
  347. ----
  348. Before adding the text field to the UI, let's improve the usability a bit
  349. and make a short exercise to compose better components from lower level UI
  350. components. The search field can naturally be cleared with the keyboard, but let's
  351. add a clear button next to the text field. Start by adding the following lines
  352. to the init method, for example right after your _filterText_ configuration:
  353. [source,java]
  354. ----
  355. Button clearFilterTextBtn = new Button(VaadinIcons.CLOSE);
  356. clearFilterTextBtn.setDescription("Clear the current filter");
  357. clearFilterTextBtn.addClickListener(e -> filterText.clear());
  358. ----
  359. Vaadin contains a set of built in icons, from which we use the "X" icon,
  360. _VaadinIcons.CLOSE_, here, which most users will recognise as a functionality to clear
  361. the value. If we set the description to a component, it will be shown as a
  362. tooltip for those users who hover the cursor over the button and wonder what to
  363. do with it. In the click listener, we simply clear the text from the field.
  364. Vaadin contains lots of different kinds of layouts. The simplest way to align
  365. the text field and the button next to each other would be to use a
  366. HorizontalLayout. An alternative way we use here is using a CssLayout, which is
  367. a lightweight layout that is easy to customize with css. Even if you wouldn't
  368. want to play with CSS yourself, you can often use one of the existing style
  369. rules in the default https://demo.vaadin.com/valo-theme[_Valo_] theme. The following snippet will create a nice
  370. compact "composition" of both the TextField and the clear button. Add these
  371. lines to the init method right after you configured the _clearFilterTextBtn_:
  372. [source,java]
  373. ----
  374. CssLayout filtering = new CssLayout();
  375. filtering.addComponents(filterText, clearFilterTextBtn);
  376. filtering.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
  377. ----
  378. Finally, *change* the line in the init method that currently adds only the grid,
  379. to add both _filtering_ composition and the _grid_ to the main _layout_ of the
  380. application.
  381. [source,java]
  382. ----
  383. layout.addComponents(filtering, grid);
  384. ----
  385. Now it is a good place to save your changes and try them in your browser.
  386. [[framework.tutorial.form]]
  387. == Creating a form to edit Customer objects
  388. To edit and add Customer objects we need to create a form, that edits the
  389. values in our domain objects. This tutorial has two alternative methods to do
  390. that. Pick either of them.
  391. [[framework.tutorial.form.designer]]
  392. === Creating a form using Vaadin Designer
  393. TIP: Starting from this step directly? https://github.com/vaadin/tutorial/archive/v8-step5.zip[Download the project] for this step, extract the zip file and choose menu:Import...[Maven>Existing Maven project].
  394. The form to edit Customer objects can be built using several methods of which
  395. the visual composition by drag 'n' drop is the most intuitive. Vaadin
  396. Designer is an Eclipse plugin that you can install and do WYSIWYG editing of
  397. your view code. We'll use it to create the form and then hook the editing logic
  398. to it with Java.
  399. TIP: If you are using another IDE or just prefer to compose your user interface
  400. with code, take the alternative step, <<Creating a form using plain Java>>,
  401. where the CustomerForm is composed using plain Java code.
  402. [[framework.tutorial.form.designer.install]]
  403. ==== Installing Vaadin Designer
  404. Vaadin Designer comes as an integrated part of Vaadin Plugin for Eclipse. It can
  405. be installed easily via Eclipse Marketplace. Choose menu:Help[Eclipse Marketplace]
  406. In the dialog, just search for Vaadin and click _install_ to mark it for
  407. installation. Clicking _Install Now_ will take you to choose the modules you want
  408. and accept the license agreement.
  409. [[figure.framework.tutorial.plugin-install]]
  410. .Selecting Vaadin Plugin for Eclipse for installation in Eclipse Marketplace
  411. image::img/pluginEclipseMarketPlace2.jpg[]
  412. If you get a security warning about the software containing unsigned content,
  413. just accept the warning by clicking OK. After installation, Eclipse asks if you
  414. want to restart. Click Yes.
  415. TIP: When you use Vaadin Designer for the first time in the next
  416. step, it will ask for a license key. Get a key from
  417. https://vaadin.com/designer. If you are not willing to buy a license now, just
  418. acquire a trial license.
  419. [[framework.tutorial.form.designer.create]]
  420. ==== Creating the form design
  421. The following screencast will show you how to produce the
  422. _CustomerFormDesign.html_, a design file we need in this tutorial. Use pause and
  423. slow motion to follow better what is being done in the video. Feel free to get creative!
  424. video::zLE2YfLB1MM[youtube, width="640", height="400"]
  425. TIP: At any point of the process, you can also switch to the markup mode where
  426. you can edit the raw content of the .html file. If you wish to take a shortcut
  427. or think you did something wrong when using the designer, you can just
  428. copy-paste the content of https://github.com/vaadin/tutorial/blob/master/src/main/resources/my/vaadin/app/CustomerFormDesign.html[the final state] to your own .html file.
  429. TIP: With Vaadin Framework 8, make following things differently:
  430. For status' NativeSelect Component, set Itemtype as CustomerStatus enum.
  431. Use DateField Component for birthday, instead of PopupDateField.
  432. At this point we only have a static mockup of the actual UI. To implement a
  433. functional form component, we need some Java code as well. Vaadin Designer
  434. automatically creates a similarly named Java class, but a good habit is to never touch the auto-generated file, in this case the
  435. CustomerFormDesign.java file. If you'd introduce a new field to your form,
  436. your changes to CustomerFormDesign would be overridden by the tooling. Instead,
  437. we'll create a class called CustomerForm which inherits from the auto-generated
  438. CustomerFormDesign class.
  439. Start by creating a new Java class with the name CustomerForm. In Eclipse, right
  440. click on the "my.vaadin.app" package and choose menu:New[Class]. Type in the
  441. name _CustomerForm_, define the superclass as
  442. _my.vaadin.app.CustomerFormDesign_ and click _finish_.
  443. From the superclass, we inherit all the UI elements that we named when using
  444. the designer. E.g. by simply referencing to "save" field in the CustomerForm,
  445. we'll have access to the save button we previously created.
  446. We will later need a reference to the currently edited Customer object,
  447. CustomerService and the MyUI that uses this class. Add these fields and a
  448. basic constructor that accepts MyUI as a parameter to the CustomerForm class:
  449. [source,java]
  450. ----
  451. private CustomerService service = CustomerService.getInstance();
  452. private Customer customer;
  453. private MyUI myUI;
  454. public CustomerForm(MyUI myUI) {
  455. this.myUI = myUI;
  456. }
  457. ----
  458. Although the form is not yet fully functional, you might want to see what it
  459. looks like at this point. Add it as a field to the _MyUI_ class:
  460. [source,java]
  461. ----
  462. private CustomerForm form = new CustomerForm(this);
  463. ----
  464. Now let's modify the init method in MyUI to show the form. Let's wrap both the
  465. Grid and the CustomerForm in a horizontal layout and configure the Grid to use
  466. all of the available space more efficiently. Replace the line
  467. *layout.addComponents(filtering, grid);* with the following:
  468. [source,java]
  469. ----
  470. HorizontalLayout main = new HorizontalLayout(grid, form);
  471. main.setSizeFull();
  472. grid.setSizeFull();
  473. main.setExpandRatio(grid, 1);
  474. layout.addComponents(filtering, main);
  475. ----
  476. If you now save your changes and reload your application page in a browser,
  477. you should see your CustomerForm next to the grid that lists your
  478. existing entities.
  479. Let's get back to the CustomerForm. The first thing we'll need is to populate
  480. the options for the select. To add all enum values as valid selections, add the
  481. following line to the constructor:
  482. [source,java]
  483. ----
  484. status.setItems(CustomerStatus.values());
  485. ----
  486. Let's also improve the UX a bit. When building the design, we already
  487. emphasized the save button with a ValoTheme.BUTTON_PRIMARY style name. Thus, it
  488. would be natural if the enter-key would do the same action as clicking the
  489. save button. Assign a keyboard shortcut to the save button with this line in the
  490. constructor:
  491. [source,java]
  492. ----
  493. save.setClickShortcut(KeyCode.ENTER);
  494. ----
  495. To finish our form, we need to create a public API that we will use in the next part from MyUI, to pass in a Customer object that the form should edit.
  496. We will also add some logic to actually save the changes.
  497. We'll start by adding a [classname]#Binder# as a field to the [classname]#CustomerForm# class:
  498. [source,java]
  499. ----
  500. private Binder<Customer> binder = new Binder<>(Customer.class);
  501. ----
  502. In the constructor of the CustomerForm class add the following line to configure
  503. the Binder:
  504. [source,java]
  505. ----
  506. binder.bindInstanceFields(this);
  507. ----
  508. This configures the Binder to use all the similary named editor fields in
  509. this form to bind their values with their counterpart in the Customer class.
  510. For example, the _CustomerForm.firstName_ TextField will be bound to the
  511. Customer.firstName property.
  512. Create a setter method for the Customer field. Just type _setCus_ in the body of the
  513. class and hit autocomplete (kbd:[Ctrl+Space]) and Eclipse will create a method
  514. stub for you. Complete it with the following implementation:
  515. [source,java]
  516. ----
  517. public void setCustomer(Customer customer) {
  518. this.customer = customer;
  519. binder.setBean(customer);
  520. // Show delete button for only customers already in the database
  521. delete.setVisible(customer.isPersisted());
  522. setVisible(true);
  523. firstName.selectAll();
  524. }
  525. ----
  526. In addition to saving the reference of the currently edited Customer object, we are
  527. calling the _Binder.setBean_ method. This will initialise all
  528. fields in the form and automatically update the values in the domain objects as
  529. the corresponding field value changes in the user interface.
  530. TIP: If the naming convention based databinding doesn't fit your needs, you
  531. can use
  532. https://www.vaadin.com/api/com/vaadin/data/fieldgroup/PropertyId.html[PropertyId]
  533. annotation on fields to explicitly declare the edited property.
  534. We'll also want to ensure the form is visible and that focus goes to the
  535. firstName field to improve user experience. As we will be using the form to
  536. edit both new non-persisted objects and existing customers, we will also show
  537. the delete button only for customers that are already persisted in the backend.
  538. The last thing we need to do is to handle save and delete button clicks. Add
  539. the following methods to the CustomerForm class:
  540. [source,java]
  541. ----
  542. private void delete() {
  543. service.delete(customer);
  544. myUI.updateList();
  545. setVisible(false);
  546. }
  547. private void save() {
  548. service.save(customer);
  549. myUI.updateList();
  550. setVisible(false);
  551. }
  552. ----
  553. Finally, we'll add listeners to the buttons to call these methods. Adding these
  554. simple lambda expressions to the constructor will take care of that:
  555. [source,java]
  556. ----
  557. save.addClickListener(e -> this.save());
  558. delete.addClickListener(e -> this.delete());
  559. ----
  560. TIP: For a truly re-usable form component in a real life project, you'd want to
  561. introduce an interface to replace the myUI field or, even better, use an event
  562. system like https://vaadin.com/wiki/-/wiki/main/Events+and+contexts[CDI events]
  563. to completely decouple the components. We'll leave that out of this tutorial for
  564. simplicity.
  565. [[framework.tutorial.form.java]]
  566. === Creating a form using plain Java
  567. TIP: Starting from this step directly? https://github.com/vaadin/tutorial/archive/v8-step5.zip[Download the project] for this step, extract the zip file and choose menu:Import...[Maven>Existing Maven project].
  568. This is an alternative step to the <<Creating a form using Vaadin Designer>>,
  569. where you'll build the form UI programmatically in plain Java. If you already
  570. completed the step using Vaadin Designer, you can proceed to
  571. <<Connecting the form to the application>>.
  572. The following video shows how to create a form using plain Java:
  573. video::jOhkclbdwp0[youtube, width="640", height="400"]
  574. Start by creating a new Java class with the name CustomerForm. In Eclipse right
  575. click on the "my.vaadin.app" package and choose menu:New[Class]. Type in the
  576. name _CustomerForm_, define the superclass as _com.vaadin.ui.FormLayout_ and
  577. click _finish_.
  578. In the form, we'll need editor fields for each property in our Customer domain
  579. class. There are different kinds of fields in Vaadin for editing different kinds
  580. of properties. In this example, we'll use a TextField, a DateField and a
  581. NativeSelect. Add the following field declarations and action buttons as Java
  582. fields to the CustomerForm:
  583. [source,java]
  584. ----
  585. private TextField firstName = new TextField("First name");
  586. private TextField lastName = new TextField("Last name");
  587. private TextField email = new TextField("Email");
  588. private NativeSelect<CustomerStatus> status = new NativeSelect<>("Status");
  589. private DateField birthdate = new DateField("Birthday");
  590. private Button save = new Button("Save");
  591. private Button delete = new Button("Delete");
  592. ----
  593. Also, we will later need a reference to the currently edited Customer object,
  594. CustomerService and the MyUI that uses this class. Add these fields and a
  595. basic constructor that accepts MyUI as a parameter to the CustomerForm class:
  596. [source,java]
  597. ----
  598. private CustomerService service = CustomerService.getInstance();
  599. private Customer customer;
  600. private MyUI myUI;
  601. public CustomerForm(MyUI myUI) {
  602. this.myUI = myUI;
  603. setSizeUndefined();
  604. HorizontalLayout buttons = new HorizontalLayout(save, delete);
  605. addComponents(firstName, lastName, email, status, birthdate, buttons);
  606. }
  607. ----
  608. In the constructor we make the form size undefined, which practically means it
  609. will consume the minimum space defined by its content. Then we'll just add all
  610. the fields to the CustomerForm and add action buttons to the bottom - side-by-side
  611. using a HorizontalLayout. Although the form is not yet fully functional, you
  612. might want to see what it looks like at this point. Add it as a field to the MyUI
  613. class:
  614. [source,java]
  615. ----
  616. private CustomerForm form = new CustomerForm(this);
  617. ----
  618. Now let's modify the init method in MyUI to show the form. Let's wrap both the
  619. Grid and the CustomerForm in a horizontal layout and configure the Grid to use
  620. all of the available space more efficiently. Replace the line
  621. *layout.addComponents(filtering, grid);* with the following:
  622. [source,java]
  623. ----
  624. HorizontalLayout main = new HorizontalLayout(grid, form);
  625. main.setSizeFull();
  626. grid.setSizeFull();
  627. main.setExpandRatio(grid, 1);
  628. layout.addComponents(filtering, main);
  629. ----
  630. When you now save your changes and reload your application page in your browser,
  631. you should see your CustomerForm next to the grid that lists your
  632. existing entities.
  633. Let's get back to the CustomerForm. The first thing we'll need is to populate
  634. the options for the select. To add all enum values as valid selections, add the
  635. following line to the constructor:
  636. [source,java]
  637. ----
  638. status.setItems(CustomerStatus.values());
  639. ----
  640. Let's also improve the UX a bit. The most common thing your users will want to
  641. do with this kind of form is to save it. Let's decorate the button with a style
  642. name that makes it more prominent in the UI and give it a keyboard shortcut -
  643. simply an enter hit in this case:
  644. [source,java]
  645. ----
  646. save.setStyleName(ValoTheme.BUTTON_PRIMARY);
  647. save.setClickShortcut(KeyCode.ENTER);
  648. ----
  649. To finish our form, we need to create a public API that we will use in the next
  650. part from the MyUI, to pass in a Customer object that the form should edit. We
  651. will also add some logic to actually save the changes. We'll start by adding a
  652. _Binder_ as a field to the _CustomerForm_ class:
  653. [source,java]
  654. ----
  655. private Binder<Customer> binder = new Binder<>(Customer.class);
  656. ----
  657. In the constructor of the CustomerForm class add the following line to configure
  658. the Binder:
  659. [source,java]
  660. ----
  661. binder.bindInstanceFields(this);
  662. ----
  663. This configures the Binder to use all the similary named editor fields in
  664. this form to bind their values with their counterpart in the Customer class.
  665. For example, the _CustomerForm.firstName_ TextField will be bound to the
  666. Customer.firstName property.
  667. Create a setter method for the Customer field. Just type _setCus_ in the body of the
  668. class and hit autocomplete (kbd:[Ctrl+Space]) and Eclipse will create a method
  669. stub for you. Complete it with the following implementation:
  670. [source,java]
  671. ----
  672. public void setCustomer(Customer customer) {
  673. this.customer = customer;
  674. binder.setBean(customer);
  675. // Show delete button for only customers already in the database
  676. delete.setVisible(customer.isPersisted());
  677. setVisible(true);
  678. firstName.selectAll();
  679. }
  680. ----
  681. In addition to saving the reference of the currently edited Customer object, we are
  682. calling the _Binder.setBean_ method. This will initialise all
  683. fields in the form and automatically update the values in the domain objects as
  684. the corresponding field value changes in the user interface.
  685. TIP: If the naming convention based databinding doesn't fit your needs, you
  686. can use
  687. https://www.vaadin.com/api/com/vaadin/annotations/PropertyId.html[PropertyId]
  688. annotation on fields to explicitly declare the edited property.
  689. We'll also want to ensure the form is visible and that the focus goes to the
  690. firstName field to improve the user experience. As we will be using the form to
  691. edit both new non-persisted objects and existing customers, we will also show
  692. the delete button only for customers that are already persisted in the backend.
  693. The last thing we need to do is to handle save and delete button clicks. Add
  694. the following methods to the CustomerForm class:
  695. [source,java]
  696. ----
  697. private void delete() {
  698. service.delete(customer);
  699. myUI.updateList();
  700. setVisible(false);
  701. }
  702. private void save() {
  703. service.save(customer);
  704. myUI.updateList();
  705. setVisible(false);
  706. }
  707. ----
  708. Finally, we'll add listeners to the buttons to call these methods. Adding these
  709. simple lambda expressions to the constructor will take care of that:
  710. [source,java]
  711. ----
  712. save.addClickListener(e -> this.save());
  713. delete.addClickListener(e -> this.delete());
  714. ----
  715. TIP: For a truly re-usable form component in a real life project, you'd want to
  716. introduce an interface to replace the myUI field or, even better, use an event
  717. system like https://vaadin.com/wiki/-/wiki/main/Events+and+contexts[CDI events]
  718. to completely decouple the components. We'll leave that out of this tutorial for
  719. simplicity.
  720. [[framework.tutorial.form-connection]]
  721. == Connecting the form to the application
  722. TIP: Starting from this step directly? https://github.com/vaadin/tutorial/archive/v8-step6.zip[Download the project] for this step, extract the zip file and choose menu:Import...[Maven>Existing Maven project].
  723. In this part, we'll use the CustomerForm class, which we created in the
  724. previous step, from the MyUI class. We will use it for both editing the existing
  725. customers and creating new ones.
  726. The following video shows how to do this step of the tutorial:
  727. video::eMCWf3PfXLs[youtube, width="640", height="400"]
  728. In the previous part, we already added the form to the _MyUI_ to see what it looks
  729. like. By default, we want it to be invisible, so let's first hide it
  730. by adding this line to the _init_ method of MyUI class:
  731. [source,java]
  732. ----
  733. form.setVisible(false);
  734. ----
  735. To edit the customer chosen from the Grid, add the following selection listener to
  736. the end of the _init_ method:
  737. [source,java]
  738. ----
  739. grid.asSingleSelect().addValueChangeListener(event -> {
  740. if (event.getValue() == null) {
  741. form.setVisible(false);
  742. } else {
  743. form.setCustomer(event.getValue());
  744. }
  745. });
  746. ----
  747. In the listener, we simply take the Customer object of the selected row and pass it to
  748. the CustomerForm for editing. In the previous step, we added a side effect to the
  749. _setCustomer_ method that will bind the domain object to the corresponding fields
  750. and make it visible. If the selection is empty, we'll hide the form.
  751. To allow users to also create new customer records, we'll create a simple "Add
  752. customer button" to the top of the UI, right next to the _filtering_ composition
  753. we have already built from a CssLayout, a TextField and a Button. Introduce the new
  754. Button with a click listener, by adding the following lines to the _init_ method,
  755. right after where you introduced the _filtering_ composition:
  756. [source,java]
  757. ----
  758. Button addCustomerBtn = new Button("Add new customer");
  759. addCustomerBtn.addClickListener(e -> {
  760. grid.asSingleSelect().clear();
  761. form.setCustomer(new Customer());
  762. });
  763. ----
  764. In the click listener, we first clear a possible selection from the grid and then
  765. instantiate a new Customer object and pass that to the form for editing.
  766. To add it beside our _filtering_ composition, we can use a HorizontalLayout to
  767. create a toolbar where we place both components. First, introduce a toolbar like
  768. this after the previously created _addCustomerBtn_:
  769. [source,java]
  770. ----
  771. HorizontalLayout toolbar = new HorizontalLayout(filtering, addCustomerBtn);
  772. ----
  773. And, again, *replace* the line that populates your main layout to add the
  774. toolbar instead of just the filtering composition, which we just moved to the
  775. _toolbar_ layout.
  776. [source,java]
  777. ----
  778. layout.addComponents(toolbar, main);
  779. ----
  780. All planned features are now done. You can save the changes and play around with
  781. the application. If something went wrong, you can also download an example of
  782. https://github.com/vaadin/tutorial[the final application] and see what went wrong.
  783. [[framework.tutorial.next]]
  784. == It works! What next?
  785. Congratulations! Users can now create, read, update and delete customer records
  786. stored in the demo backend and you have completed creating your first CRUD UI
  787. with Vaadin.
  788. If you are an experienced Java developer, you are probably already full of ideas of
  789. how you can use your existing skills and create new shiny web UIs for your
  790. existing Java apps. If you want more ideas of how to create full stack
  791. applications, you might, for example, go through the
  792. http://spring.io/guides/gs/crud-with-vaadin/[Creating CRUD UI with Vaadin] guide
  793. and create a bit similar UI with a real database backend implemented with Spring
  794. Data JPA. We have also collected a couple of other resources for an easy
  795. start in your Vaadin developer career.
  796. * https://vaadin.com/docs/-/part/framework/introduction/intro-overview.html[Vaadin online documentation]
  797. * https://vaadin.com/full-stack-starter[Bakery App Starter for Vaadin Framework 8 and Spring] - A fully functional and tested full stack application for you to use as a starting point and a reference implementation on how business grade Vaadin applications should be made.
  798. * http://spring.io/guides/gs/crud-with-vaadin/[Creating CRUD UI with Vaadin] - the tutorial for your first Vaadin application using a Spring based backend.
  799. * https://github.com/mstahv/jpa-invoicer[Jave EE example app] - a Vaadin app example for creating invoices that uses Java EE backend, Apache DeltaSpike Data for simple JPA layer, OAuth2 based login, PDF generation etc.
  800. * http://vaadin.com/directory[Directory] - a vast source of awesome Vaadin add-ons