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.

components-grid.asciidoc 33KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. ---
  2. title: Grid
  3. order: 24
  4. layout: page
  5. ---
  6. [[components.grid]]
  7. = [classname]#Grid#
  8. ifdef::web[]
  9. [.sampler]
  10. image:{live-demo-image}[alt="Live Demo", link="http://demo.vaadin.com/sampler/#ui/grids-and-trees/grid"]
  11. endif::web[]
  12. [[components.grid.overview]]
  13. == Overview
  14. [classname]#Grid# is for displaying and editing tabular data laid out in rows
  15. and columns. At the top, a __header__ can be shown, and a __footer__ at the
  16. bottom. In addition to plain text, the header and footer can contain HTML and
  17. components. Having components in the header allows implementing filtering
  18. easily. The grid data can be sorted by clicking on a column header;
  19. shift-clicking a column header enables secondary sorting criteria.
  20. [[figure.components.grid.features]]
  21. .A [classname]#Grid#
  22. image::img/grid-features.png[width=70%, scaledwidth=100%]
  23. The data area can be scrolled both vertically and horizontally. The leftmost
  24. columns can be frozen, so that they are never scrolled out of the view. The data
  25. is loaded lazily from the server, so that only the visible data is loaded. The
  26. smart lazy loading functionality gives excellent user experience even with low
  27. bandwidth, such as mobile devices.
  28. The grid data can be edited with a row-based editor after double-clicking a row.
  29. The fields are set explicitly, and bound to data.
  30. Grid is fully themeable with CSS and style names can be set for all grid
  31. elements. For data rows and cells, the styles can be generated with a row or
  32. cell style generator.
  33. Finally, [classname]#Grid# is designed to be extensible and used just as well
  34. for client-side development - its GWT API is nearly identical to the server-side
  35. API, including data binding.
  36. [[components.grid.data]]
  37. == Binding to Data
  38. [classname]#Grid# is normally used by binding it to a container data source,
  39. described in
  40. <<dummy/../../../framework/datamodel/datamodel-overview.asciidoc#datamodel.overview,"Binding Components to Data">>.
  41. By default, it is bound to List of items. You can set the items in the constructor or with
  42. [methodname]#setItems()# method.
  43. For example, if you have a list of beans, you could add to a [classname]#Grid# as follows
  44. [source, java]
  45. ----
  46. // Have some data
  47. List<Person> people = Lists.newArrayList(
  48. new Person("Nicolaus Copernicus", 1543),
  49. new Person("Galileo Galilei", 1564),
  50. new Person("Johannes Kepler", 1571));
  51. // Create a grid bound to the list
  52. Grid<Person> grid = new Grid<>(people);
  53. grid.addColumn("Name", Person::getName);
  54. grid.addColumn("Year of birth", Person::getBirthYear);
  55. layout.addComponent(grid);
  56. ----
  57. In addition to list you can pass items individually:
  58. [source, java]
  59. ----
  60. grid.setItems(new Person("Nicolaus Copernicus", 1543),
  61. new Person("Galileo Galilei", 1564));
  62. ----
  63. Note that you can not use [methodname]#addRow()# to add items if the container
  64. is read-only or has read-only columns, such as generated columns.
  65. [[components.grid.selection]]
  66. == Handling Selection Changes
  67. Selection in [classname]#Grid# is handled a bit differently from other selection
  68. components, as it is not an [classname]#AbstractSelect#. Grid supports both
  69. single and multiple selection, defined by the __selection model__. Selection
  70. events can be handled with a [interfacename]#SelectionListener#.
  71. [[components.grid.selection.mode]]
  72. === Selection Models
  73. A [classname]#Grid# can be set to be in [literal]#++SINGLE++# (default),
  74. [literal]#++MULTI++#, or [literal]#++NONE++# selection mode, defined in the
  75. [interfacename]#SelectionMode# enum.
  76. [source, java]
  77. ----
  78. // Use single-selection mode (default)
  79. grid.setSelectionMode(SelectionMode.SINGLE);
  80. ----
  81. Empty (null) selection is allowed by default, but can be disabled
  82. with [methodname]#setDeselectAllowed()# in single-selection mode.
  83. [source, java]
  84. ----
  85. // Pre-select 3rd item from the person list
  86. grid.select(personList.get(2));
  87. ----
  88. [[components.grid.selection.single]]
  89. === Handling Selection
  90. Changes in the selection can be handled with a
  91. [interfacename]#SelectionListener#. You need to implement the
  92. [methodname]#select()# method, which gets a [classname]#SelectionEvent# as
  93. parameter. In addition to selection, you can handle clicks on rows or cells with
  94. a [interfacename]#CellClickListener#.
  95. You can get the new selection from the selection event with
  96. [methodname]#getSelected()#, which returns a set of items, or more simply
  97. from the grid.
  98. For example:
  99. [source, java]
  100. ----
  101. grid.addSelectionListener(selectionEvent -> {
  102. // Get selection from the selection model
  103. Collection<Person> selectedPersons =
  104. selectionEvent.getSelected();
  105. if (!selectedPersons.isEmpty())
  106. Notification.show("Selected " + selectedPersons);
  107. else
  108. Notification.show("Nothing selected");
  109. });
  110. ----
  111. The current selection can be obtained from the [classname]#Grid# object by
  112. [methodname]#getSelectedItem()# or [methodname]#getSelectedItems()#, which return
  113. one (in single-selection mode) or all (in multi-selection mode) selected items.
  114. [WARNING]
  115. ====
  116. If you change the data source for a grid, it will clear the selection. To keep
  117. the previous selection you must reset the selection afterwards using the
  118. [methodname]#select()# method.
  119. ====
  120. [[components.grid.selection.multi]]
  121. === Multiple Selection
  122. In the multiple selection mode, a user can select multiple items by clicking on
  123. the checkboxes in the leftmost column, or by using the kbd:[Space] to select/deselect the currently focused row.
  124. Space bar is the default key for toggling the selection, but it can be customized.
  125. [[figure.components.grid.selection.multi]]
  126. .Multiple Selection in [classname]#Grid#
  127. image::img/grid-selection-multi.png[width=50%, scaledwidth=75%]
  128. You can use [methodname]#select()# to add items to the selection.
  129. [source, java]
  130. ----
  131. // Grid in multi-selection mode
  132. Grid<Person> grid = Grid<>(personList)
  133. grid.setSelectionMode(SelectionMode.MULTI);
  134. // Items 2-4
  135. personList.subList(2,3).forEach(grid::select);
  136. ----
  137. The current selection can be read with [methodname]#getSelected()#
  138. in the [classname]#Grid#.
  139. [source, java]
  140. ----
  141. // Allow deleting the selected items
  142. Button delSelected = new Button("Delete Selected", e -> {
  143. // Delete all selected data items
  144. for (Person person: selection.getSelected())
  145. personList.remove(person);
  146. // Disable after deleting
  147. e.getButton().setEnabled(false);
  148. // Reset grid content from the list
  149. grid.setItems(personList);
  150. });
  151. delSelected.setEnabled(!grid.getSelected().isEmpty());
  152. ----
  153. Changes in the selection can be handled with a
  154. [interfacename]#SelectionListener#. The selection event object provides
  155. [methodname]#getAdded()# and [methodname]#getRemoved()# to allow determining the
  156. differences in the selection change.
  157. [source, java]
  158. ----
  159. // Handle selection changes
  160. grid.addSelectionListener(selection -> { // Java 8
  161. Notification.show(selection.getAdded().size() +
  162. " items added, " +
  163. selection.getRemoved().size() +
  164. " removed.");
  165. // Allow deleting only if there's any selected
  166. deleteSelected.setEnabled(
  167. grid.getSelectedRows().size() > 0);
  168. });
  169. ----
  170. [[components.grid.selection.clicks]]
  171. === Focus and Clicks
  172. In addition to selecting rows, you can focus individual cells. The focus can be
  173. moved with arrow keys and, if editing is enabled, pressing kbd:[Enter] opens the
  174. editor. Normally, pressing kbd:[Tab] or kbd:[Shift+Tab] moves the focus to another component,
  175. as usual.
  176. When editing or in unbuffered mode, kbd:[Tab] or kbd:[Shift+Tab] moves the focus to the next or
  177. previous cell. The focus moves from the last cell of a row forward to the
  178. beginning of the next row, and likewise, from the first cell backward to the
  179. end of the previous row. Note that you can extend [classname]#DefaultEditorEventHandler#
  180. to change this behavior.
  181. With the mouse, you can focus a cell by clicking on it. The clicks can be handled
  182. with an [interfacename]#ItemClickListener#. The [classname]#ItemClickEvent#
  183. object contains various information, most importantly the ID of the clicked row
  184. and column.
  185. [source, java]
  186. ----
  187. grid.addCellClickListener(event ->
  188. Notification.show("Value: " + event.getItem());
  189. ----
  190. The clicked grid cell is also automatically focused.
  191. The focus indication is themed so that the focused cell has a visible focus
  192. indicator style by default, while the row does not. You can enable row focus, as
  193. well as disable cell focus, in a custom theme. See <<components.grid.css>>.
  194. [[components.grid.columns]]
  195. == Configuring Columns
  196. Columns are normally defined in the container data source. The
  197. [methodname]#addColumn()# method can be used to add columns to [classname]#Grid#.
  198. Column configuration is defined in [classname]#Grid.Column# objects, which can
  199. be obtained from the grid with [methodname]#getColumns()#.
  200. [source, java]
  201. ----
  202. Column<Date> bornColumn = grid.addColumn(Person:getBirthDate);
  203. bornColumn.setHeaderCaption("Born date");
  204. ----
  205. In the following, we describe the basic column configuration.
  206. [[components.grid.columns.order]]
  207. === Column Order
  208. You can set the order of columns with [methodname]#setColumnOrder()# for the
  209. grid. Columns that are not given for the method are placed after the specified
  210. columns in their natural order.
  211. [source, java]
  212. ----
  213. grid.setColumnOrder(firstnameColumn, lastnameColumn,
  214. bornColumn, birthplaceColumn,
  215. diedColumn);
  216. ----
  217. Note that the method can not be used to hide columns. You can hide columns with
  218. the [methodname]#removeColumn()#, as described later.
  219. [[components.grid.columns.removing]]
  220. === Hiding and Removing Columns
  221. Columns can be hidden by calling [methodname]#setHidden()# in [classname]#Column#.
  222. Furthermore, you can set the columns user hideable using method
  223. [methodname]#setHideable()#.
  224. Columns can be removed with [methodname]#removeColumn()# and
  225. [methodname]#removeAllColumns()#. To restore a previously removed column,
  226. you can call [methodname]#addColumn()#.
  227. [[components.grid.columns.captions]]
  228. === Column Captions
  229. Column captions are displayed in the grid header. You can set the header caption
  230. explicitly through the column object with [methodname]#setHeaderCaption()#.
  231. [source, java]
  232. ----
  233. Column<Date> bornColumn = grid.addColumn(Person:getBirthDate);
  234. bornColumn.setHeaderCaption("Born date");
  235. ----
  236. This is equivalent to setting it with [methodname]#setText()# for the header
  237. cell; the [classname]#HeaderCell# also allows setting the caption in HTML or as
  238. a component, as well as styling it, as described later in
  239. <<components.grid.headerfooter>>.
  240. [[components.grid.columns.width]]
  241. === Column Widths
  242. Columns have by default undefined width, which causes automatic sizing based on
  243. the widths of the displayed data. You can set column widths explicitly by pixel
  244. value with [methodname]#setWidth()#, or relatively using expand ratios with
  245. [methodname]#setExpandRatio()#.
  246. When using expand ratios, the columns with a non-zero expand ratio use the extra
  247. space remaining from other columns, in proportion to the defined ratios.
  248. You can specify minimum and maximum widths for the expanding columns with
  249. [methodname]#setMinimumWidth()# and [methodname]#setMaximumWidth()#,
  250. respectively.
  251. The user can resize columns by dragging their separators with the mouse. When resized manually,
  252. all the columns widths are set to explicit pixel values, even if they had
  253. relative values before.
  254. [[components.grid.columns.frozen]]
  255. === Frozen Columns
  256. You can set the number of columns to be frozen with
  257. [methodname]#setFrozenColumnCount()#, so that they are not scrolled off when
  258. scrolling horizontally.
  259. [source, java]
  260. ----
  261. grid.setFrozenColumnCount(2);
  262. ----
  263. Setting the count to [parameter]#0# disables frozen data columns; setting it to
  264. [parameter]#-1# also disables the selection column in multi-selection mode.
  265. [[components.grid.generatedcolumns]]
  266. == Generating Columns
  267. Columns with values computed from other columns can be simply added by using
  268. lambdas:
  269. [source, java]
  270. ----
  271. // Add generated full name column
  272. Column<String> fullNameColumn = grid.addColumn(person ->
  273. person.getFirstName() + " " + person.getLastName());
  274. fullNameColumn.setHeaderCaption("Full name");
  275. ----
  276. [[components.grid.renderer]]
  277. == Column Renderers
  278. A __renderer__ is a feature that draws the client-side representation of a data
  279. value. This allows having images, HTML, and buttons in grid cells.
  280. [[figure.components.grid.renderer]]
  281. .Column renderers: image, date, HTML, and button
  282. image::img/grid-renderers.png[width=75%, scaledwidth=100%]
  283. Renderers implement the [interfacename]#Renderer# interface.
  284. You set the column renderer in the [classname]#Grid.Column# object as follows:
  285. [source, java]
  286. ----
  287. Column<Integer> bornColumn = grid.addColumn(Person:getBirthYear);
  288. ...
  289. Grid.Column bornColumn = grid.getColumn("born");
  290. bornColumn.setRenderer(new NumberRenderer("born in %d AD"));
  291. ----
  292. Renderers require a specific data type for the column. To convert to a property
  293. type to a type required by a renderer, you can pass an optional
  294. [interfacename]#Converter# to [methodname]#setRenderer()#, as described later in
  295. this section. A converter can also be used to (pre)format the property values.
  296. The converter is run on the server-side, before sending the values to the
  297. client-side to be rendered with the renderer.
  298. The following renderers are available, as defined in the server-side
  299. [package]#com.vaadin.ui.renderers# package:
  300. [classname]#ButtonRenderer#:: Renders the data value as the caption of a button. A [interfacename]#RendererClickListener# can be given to handle the button clicks.
  301. ifdef::web[]
  302. +
  303. Typically, a button renderer is used to display buttons for operating on a data
  304. item, such as edit, view, delete, etc. It is not meaningful to store the button
  305. captions in the data source, rather you want to generate them, and they are
  306. usually all identical.
  307. +
  308. [source, java]
  309. ----
  310. List<Person> people = new ArrayList<>();
  311. people.add(new Person("Nicolaus Copernicus", 1473));
  312. people.add(new Person("Galileo Galilei", 1564));
  313. people.add(new Person("Johannes Kepler", 1571));
  314. // Create a grid
  315. Grid<Person> grid = new Grid(people);
  316. // Render a button that deletes the data row (item)
  317. grid.addColumn(person -> "Delete" )
  318. .setRenderer(new ButtonRenderer(clickEvent -> {
  319. people.remove(clickEvent.getValue());
  320. grid.setItems(people);
  321. });
  322. ----
  323. endif::web[]
  324. [classname]#ImageRenderer#:: Renders the cell as an image.
  325. The column type must be a [interfacename]#Resource#, as described in
  326. <<dummy/../../../framework/application/application-resources#application.resources,"Images and Other Resources">>; only [classname]#ThemeResource# and
  327. [classname]#ExternalResource# are currently supported for images in
  328. [classname]#Grid#.
  329. ifdef::web[]
  330. +
  331. [source, java]
  332. ----
  333. Column<ThemeResource> imageColumn = grid.addColumn("picture",
  334. p -> new ThemeResource("img/"+p.getLastname()+".jpg"));
  335. imageColumn.setRenderer(new ImageRenderer());
  336. ----
  337. +
  338. You also need to define the row heights so that the images fit there. You can
  339. set it in the theme for all data cells or for the column containing the images.
  340. +
  341. For the latter way, first define a CSS style name for grid and the column:
  342. +
  343. [source, java]
  344. ----
  345. grid.setStyleName("gridwithpics128px");
  346. imageColumn.setCellStyleGenerator(cell -> "imagecol");
  347. ----
  348. ifdef::web[]
  349. +
  350. Then, define the style in CSS (Sass):
  351. endif::web[]
  352. +
  353. [source, css]
  354. ----
  355. .gridwithpics128px .imagecol {
  356. height: 128px;
  357. background: black;
  358. text-align: center;
  359. }
  360. ----
  361. endif::web[]
  362. [classname]#DateRenderer#:: Formats a column with a [classname]#Date# type using string formatter. The
  363. format string is same as for [methodname]#String.format()# in Java API. The date
  364. is passed in the parameter index 1, which can be omitted if there is only one
  365. format specifier, such as "[literal]#++%tF++#".
  366. ifdef::web[]
  367. +
  368. [source, java]
  369. ----
  370. Grid.Column<Date> bornColumn = grid.addColumn(person:getBirthDate);
  371. bornColumn.setRenderer(
  372. new DateRenderer("%1$tB %1$te, %1$tY",
  373. Locale.ENGLISH));
  374. ----
  375. +
  376. Optionally, a locale can be given. Otherwise, the default locale (in the
  377. component tree) is used.
  378. endif::web[]
  379. [classname]#HTMLRenderer#:: Renders the cell as HTML.
  380. This allows formatting the cell content, as well as using HTML features such as hyperlinks.
  381. ifdef::web[]
  382. +
  383. Set the renderer in the [classname]#Grid.Column# object:
  384. +
  385. [source, java]
  386. ----
  387. Column<String> htmlColumn grid.addColumn(person ->
  388. "<a href='" + person.getDetailsUrl() + "' target='_top'>info</a>");
  389. htmlColumn.setRenderer(new HtmlRenderer());
  390. ----
  391. endif::web[]
  392. [classname]#NumberRenderer#:: Formats column values with a numeric type extending [classname]#Number#:
  393. [classname]#Integer#, [classname]#Double#, etc. The format can be specified
  394. either by the subclasses of [classname]#java.text.NumberFormat#, namely
  395. [classname]#DecimalFormat# and [classname]#ChoiceFormat#, or by
  396. [methodname]#String.format()#.
  397. ifdef::web[]
  398. +
  399. For example:
  400. +
  401. [source, java]
  402. ----
  403. // Define some columns
  404. Column<String> nameCol = grid.addColumn(person::getName);
  405. Column<Integer> bornCol = grid.addColumn(person:getBirthYear);
  406. Column<Integer> slettersCol = grid.addColumn("sletters");
  407. Column<Double> ratingCol = grid.addColumn("rating");
  408. // Use decimal format
  409. bornCol.setRenderer(new NumberRenderer(
  410. new DecimalFormat("in #### AD")));
  411. // Use textual formatting on numeric ranges
  412. slettersCol.setRenderer(new NumberRenderer(
  413. new ChoiceFormat("0#none|1#one|2#multiple")));
  414. // Use String.format() formatting
  415. ratingCol.setRenderer(new NumberRenderer(
  416. "%02.4f", Locale.ENGLISH));
  417. // Add some data rows
  418. grid.addItems(new Person("Nicolaus Copernicus", 1473, 2, 0.4),
  419. new Person("Galileo Galilei", 1564, 0, 4.2),
  420. new Person("Johannes Kepler", 1571, 1, 2.3));
  421. ----
  422. endif::web[]
  423. [classname]#ProgressBarRenderer#:: Renders a progress bar in a column with a [classname]#Double# type. The value
  424. must be between 0.0 and 1.0.
  425. ifdef::web[]
  426. +
  427. For example:
  428. +
  429. [source, java]
  430. ----
  431. // Define some columns
  432. Column<String> nameCol = grid.addColumn(person::getName);
  433. Column<Double> ratingCol = grid.addColumn("rating");
  434. ratingCol.setRenderer(new ProgressBarRenderer());
  435. // Add some data rows
  436. grid.addItems(new Person("Nicolaus Copernicus", 0.4),
  437. new Person("Galileo Galilei", 4.2),
  438. new Person("Johannes Kepler", 2.3));
  439. ----
  440. endif::web[]
  441. [classname]#TextRenderer#:: Displays plain text as is. Any HTML markup is quoted.
  442. [[components.grid.renderer.custom]]
  443. === Custom Renderers
  444. Renderers are component extensions that require a client-side counterpart. See
  445. <<dummy/../../../framework/clientsidewidgets/clientsidewidgets-grid#clientsidewidgets.grid.renderers,"Renderers">>
  446. for information on implementing custom renderers.
  447. [[components.grid.headerfooter]]
  448. == Header and Footer
  449. A grid by default has a header, which displays column names, and can have a
  450. footer. Both can have multiple rows and neighbouring header row cells can be
  451. joined to feature column groups.
  452. [[components.grid.headerfooter.adding]]
  453. === Adding and Removing Header and Footer Rows
  454. A new header row is added with [methodname]#prependHeaderRow()#, which adds it
  455. at the top of the header, [methodname]#appendHeaderRow()#, which adds it at the
  456. bottom of the header, or with [methodname]#addHeaderRowAt()#, which inserts it
  457. at the specified 0-base index. All of the methods return a
  458. [classname]#HeaderRow# object, which you can use to work on the header further.
  459. [source, java]
  460. ----
  461. // Group headers by joining the cells
  462. HeaderRow groupingHeader = grid.prependHeaderRow();
  463. ...
  464. // Create a header row to hold column filters
  465. HeaderRow filterRow = grid.appendHeaderRow();
  466. ...
  467. ----
  468. Similarly, you can add footer rows with [methodname]#appendFooterRow()#,
  469. [methodname]#prependFooterRow()#, and [methodname]#addFooterRowAt()#.
  470. [[components.grid.headerfooter.joining]]
  471. === Joining Header and Footer Cells
  472. You can join two or more header or footer cells with the [methodname]#join()#
  473. method. For header cells, the intention is usually to create column grouping,
  474. while for footer cells, you typically calculate sums or averages.
  475. [source, java]
  476. ----
  477. // Group headers by joining the cells
  478. HeaderRow groupingHeader = grid.prependHeaderRow();
  479. HeaderCell namesCell = groupingHeader.join(
  480. groupingHeader.getCell("firstname"),
  481. groupingHeader.getCell("lastname")).setText("Person");
  482. HeaderCell yearsCell = groupingHeader.join(
  483. groupingHeader.getCell("born"),
  484. groupingHeader.getCell("died"),
  485. groupingHeader.getCell("lived")).setText("Dates of Life");
  486. ----
  487. [[components.grid.headerfooter.content]]
  488. === Text and HTML Content
  489. You can set the header caption with [methodname]#setText()#, in which case any
  490. HTML formatting characters are quoted to ensure security.
  491. [source, java]
  492. ----
  493. HeaderRow mainHeader = grid.getDefaultHeaderRow();
  494. mainHeader.getCell("firstname").setText("First Name");
  495. mainHeader.getCell("lastname").setText("Last Name");
  496. mainHeader.getCell("born").setText("Born In");
  497. mainHeader.getCell("died").setText("Died In");
  498. mainHeader.getCell("lived").setText("Lived For");
  499. ----
  500. To use raw HTML in the captions, you can use [methodname]#setHtml()#.
  501. [source, java]
  502. ----
  503. namesCell.setHtml("<b>Names</b>");
  504. yearsCell.setHtml("<b>Years</b>");
  505. ----
  506. [[components.grid.headerfooter.components]]
  507. === Components in Header or Footer
  508. You can set a component in a header or footer cell with
  509. [methodname]#setComponent()#. Often, this feature is used to allow filtering, as
  510. described in <<components.grid.filtering>>, which also gives an example of the
  511. use.
  512. [[components.grid.filtering]]
  513. == Filtering
  514. The ability to include components in the grid header can be used to create
  515. filters for the grid data. Filtering is done in the container data source, so
  516. the container must be of type that implements
  517. [interfacename]#Container.Filterable#.
  518. [[figure.components.grid.filtering]]
  519. .Filtering Grid
  520. image::img/grid-filtering.png[width=50%, scaledwidth=80%]
  521. The filtering illustrated in <<figure.components.grid.filtering>> can be created
  522. as follows:
  523. [source, java]
  524. ----
  525. // Have a list of persons
  526. List<Person> persons = exampleDataSource();
  527. // Create a grid bound to it
  528. Grid<Person> grid = new Grid(persons);
  529. grid.setSelectionMode(SelectionMode.NONE);
  530. grid.setWidth("500px");
  531. grid.setHeight("300px");
  532. // Create a header row to hold column filters
  533. HeaderRow filterRow = grid.appendHeaderRow();
  534. // Set up a filter for all columns
  535. for (Column<?> col: grid.getColumns()) {
  536. HeaderCell cell = filterRow.getCell(col);
  537. // Have an input field to use for filter
  538. TextField filterField = new TextField();
  539. // Update filter When the filter input is changed
  540. filterField.addValueChangeListener(event -> {
  541. // Filter the list of items
  542. List<String> filteredList =
  543. Lists.newArrayList(personList.filter(persons,
  544. Predicates.containsPattern(event.getValue())));
  545. // Apply filtered data
  546. grid.setItems(filteredList);
  547. });
  548. cell.setComponent(filterField);
  549. }
  550. ----
  551. [[components.grid.sorting]]
  552. == Sorting
  553. A user can sort the data in a grid on a column by clicking the column header.
  554. Clicking another time on the current sort column reverses the sort direction.
  555. Clicking on other column headers while keeping the Shift key pressed adds a
  556. secondary or more sort criteria.
  557. [[figure.components.grid.sorting]]
  558. .Sorting Grid on Multiple Columns
  559. image::img/grid-sorting.png[width=50%, scaledwidth=75%]
  560. Defining sort criteria programmatically can be done with the various
  561. alternatives of the [methodname]#sort()# method. You can sort on a specific
  562. column with [methodname]#sort(Column column)#, which defaults to ascending
  563. sorting order, or [methodname]#sort(Column column, SortDirection
  564. direction)#, which allows specifying the sort direction.
  565. [source, java]
  566. ----
  567. grid.sort(nameColumn, SortDirection.DESCENDING);
  568. ----
  569. To sort on multiple columns, you need to use the fluid sort API with
  570. [methodname]#sort(Sort)#, which allows chaining sorting rules. Sorting rules are
  571. created with the static [methodname]#by()# method, which defines the primary
  572. sort column, and [methodname]#then()#, which can be used to specify any
  573. secondary sort columns. They default to ascending sort order, but the sort
  574. direction can be given with an optional parameter.
  575. [source, java]
  576. ----
  577. // Sort first by city and then by name
  578. grid.sort(Sort.by(cityColumn, SortDirection.ASCENDING)
  579. .then(nameColumn, SortDirection.DESCENDING));
  580. ----
  581. [[components.grid.editing]]
  582. == Editing
  583. Grid supports line-based editing, where double-clicking a row opens the row
  584. editor. In the editor, the input fields can be edited, as well as navigated with
  585. kbd:[Tab] and kbd:[Shift+Tab] keys. If validation fails, an error is displayed and the user
  586. can correct the inputs.
  587. To enable editing, you need to call [methodname]#setEditorEnabled(true)# for the
  588. grid.
  589. [source, java]
  590. ----
  591. Grid<Person> grid = new Grid(persons);
  592. grid.setEditorEnabled(true);
  593. ----
  594. Grid supports two row editor modes - buffered and unbuffered. The default mode is
  595. buffered. The mode can be changed with [methodname]#setBuffered(false)#
  596. [[components.grid.editing.buffered]]
  597. === Buffered Mode
  598. The editor has a [guibutton]#Save# button that commits
  599. the data item to the container data source and closes the editor. The
  600. [guibutton]#Cancel# button discards the changes and exits the editor.
  601. A row under editing is illustrated in <<figure.components.grid.editing>>.
  602. [[figure.components.grid.editing]]
  603. .Editing a Grid Row
  604. image::img/grid-editor-basic.png[width=50%, scaledwidth=75%]
  605. [[components.grid.editing.unbuffered]]
  606. === Unbuffered Mode
  607. The editor has no buttons and all changed data is committed directly
  608. to the container. If another row is clicked, the editor for the current row is closed and
  609. a row editor for the clicked row is opened.
  610. [[components.grid.editing.fields]]
  611. === Editor Fields
  612. The editor fields are configured in [classname]#Column#and bound to
  613. the bean data source with a [classname]#Binder#, which
  614. also handles tasks such as validation, as explained later.
  615. To disable editing in a particular column, you can call
  616. [methodname]#setEditorField()# in the [classname]#Column# object with
  617. [parameter]#null# parameter.
  618. In the following example, we configure a field with validation and styling:
  619. [source, java]
  620. ----
  621. // Create an editor for name
  622. TextField nameEditor = new TextField();
  623. // Custom CSS style
  624. nameEditor.addStyleName("nameeditor");
  625. // Add editor to name column
  626. nameColumn.setEditorField(nameEditor);
  627. ----
  628. Setting an editor field to [parameter]#null# deletes the currently existing
  629. editor field and makes the column non-editable.
  630. ifdef::web[]
  631. [[components.grid.editing.captions]]
  632. === Customizing Editor Buttons
  633. In the buffered mode, the editor has two buttons: [guibutton]#Save# and [guibutton]#Cancel#. You can
  634. set their captions with [methodname]#setEditorSaveCaption()# and
  635. [methodname]#setEditorCancelCaption()#, respectively.
  636. In the following example, we demonstrate one way to translate the captions:
  637. [source, java]
  638. ----
  639. // Captions are stored in a resource bundle
  640. ResourceBundle bundle = ResourceBundle.getBundle(
  641. MyAppCaptions.class.getName(),
  642. Locale.forLanguageTag("fi")); // Finnish
  643. // Localize the editor button captions
  644. grid.setEditorSaveCaption(
  645. bundle.getString(MyAppCaptions.SaveKey));
  646. grid.setEditorCancelCaption(
  647. bundle.getString(MyAppCaptions.CancelKey));
  648. ----
  649. endif::web[]
  650. [[components.grid.editing.fieldgroup]]
  651. === Binding to Data with a Binder
  652. Data binding to the item under editing is handled with a
  653. [classname]#Binder#, which you need to set with
  654. [methodname]#setEditorFieldGroup#. This is mostly useful when using
  655. special-purpose, such as to enable bean validation.
  656. For example, assuming that we want to enable bean validation for a bean such as
  657. the following:
  658. [source, java]
  659. ----
  660. public class Person implements Serializable {
  661. @NotNull
  662. @Size(min=2, max=10)
  663. private String name;
  664. @Min(1)
  665. @Max(130)
  666. private int age;
  667. ...]
  668. ----
  669. We can now use a [classname]#BeanBinder# in the [classname]#Grid# as
  670. follows:
  671. [source, java]
  672. ----
  673. Grid<Person> grid = new Grid(examplePersonList());
  674. Column<String> nameCol = grid.addColumn(Person::getName);
  675. Column<Integer> ageCol = grid.addColumn(Person::getAge);
  676. grid.setEditorEnabled(true);
  677. TextField nameEditor = new TextField();
  678. nameCol.setEditorField(nameEditor);
  679. // Enable bean validation for the data
  680. BeanBinder<Person> binder = new BeanBinder<>(Person.class);
  681. // Have some extra validation in a field
  682. binder.addField(nameEditor, "name")
  683. .addValidator(new RegexpValidator(
  684. "^\\p{Alpha}+ \\p{Alpha}+$",
  685. "Need first and last name"));
  686. grid.setEditorBinder(binder);
  687. ----
  688. To use bean validation as in the example above, you need to include an
  689. implementation of the Bean Validation API in the classpath, as described in
  690. <<dummy/../../../framework/datamodel/datamodel-itembinding#datamodel.itembinding.beanvalidation,"Bean
  691. Validation">>.
  692. ifdef::web[]
  693. [[components.grid.editing.validation]]
  694. === Handling Validation Errors
  695. The input fields are validated when the value is updated. The default
  696. error handler displays error indicators in the invalid fields, as well as the
  697. first error in the editor.
  698. [[figure.components.grid.errors]]
  699. .Editing a Grid Row
  700. image::img/grid-editor-errors.png[width=50%, scaledwidth=75%]
  701. You can modify the error handling by implementing a custom
  702. [interfacename]#EditorErrorHandler# or by extending the
  703. [classname]#DefaultEditorErrorHandler#.
  704. endif::web[]
  705. [[components.grid.scrolling]]
  706. == Programmatic Scrolling
  707. You can scroll to first item with [methodname]#scrollToStart()#, to end with
  708. [methodname]#scrollToEnd()#, or to a specific row with [methodname]#scrollTo()#.
  709. [[components.grid.stylegeneration]]
  710. == Generating Row or Cell Styles
  711. You can style entire rows or individual cells with a
  712. [interfacename]#StyleGenerator#, typically used through Java lambdas.
  713. [[components.grid.stylegeneration.row]]
  714. === Generating Row Styles
  715. You set a [interfacename]#StyleGenerator# to a grid with
  716. [methodname]#setStyleGenerator()#. The [methodname]#getStyle()# method gets a
  717. date item, and should return a style name or [parameter]#null# if
  718. no style is generated.
  719. For example, to add a style names to rows having certain values in one
  720. property of an item, you can style them as follows:
  721. [source, java]
  722. ----
  723. grid.setStyleGenerator(person -> {
  724. // Style based on alive status
  725. person.isAlive() ? null : "dead";
  726. });
  727. ----
  728. You could then style the rows with CSS as follows:
  729. [source, css]
  730. ----
  731. .v-grid-row.dead {
  732. color: gray;
  733. }
  734. ----
  735. [[components.grid.stylegeneration.cell]]
  736. === Generating Cell Styles
  737. You set a [interfacename]#StyleGenerator# to a grid with
  738. [methodname]#setStyleGenerator()#. The [methodname]#getStyle()# method gets
  739. a [classname]#CellReference#, which contains various information about the cell
  740. and a reference to the grid, and should return a style name or [parameter]#null#
  741. if no style is generated.
  742. For example, to add a style name to a specific column, you can match on
  743. the column as follows:
  744. [source, java]
  745. ----
  746. // Static style based on column
  747. bornColumn.setStyleGenerator(person -> "rightalign");
  748. ----
  749. You could then style the cells with a CSS rule as follows:
  750. [source, css]
  751. ----
  752. .v-grid-cell.rightalign {
  753. text-align: right;
  754. }
  755. ----
  756. [[components.grid.css]]
  757. == Styling with CSS
  758. [source, css]
  759. ----
  760. .v-grid {
  761. .v-grid-scroller, .v-grid-scroller-horizontal { }
  762. .v-grid-tablewrapper {
  763. .v-grid-header {
  764. .v-grid-row {
  765. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  766. }
  767. }
  768. .v-grid-body {
  769. .v-grid-row,
  770. .v-grid-row-stripe,
  771. .v-grid-row-has-data {
  772. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  773. }
  774. }
  775. .v-grid-footer {
  776. .v-grid-row {
  777. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  778. }
  779. }
  780. }
  781. .v-grid-header-deco { }
  782. .v-grid-footer-deco { }
  783. .v-grid-horizontal-scrollbar-deco { }
  784. .v-grid-editor {
  785. .v-grid-editor-cells { }
  786. .v-grid-editor-footer {
  787. .v-grid-editor-message { }
  788. .v-grid-editor-buttons {
  789. .v-grid-editor-save { }
  790. .v-grid-editor-cancel { }
  791. }
  792. }
  793. }
  794. }
  795. ----
  796. A [classname]#Grid# has an overall [literal]#++v-grid++# style. The actual grid
  797. has three parts: a header, a body, and a footer. The scrollbar is a custom
  798. element with [literal]#++v-grid-scroller++# style. In addition, there are some
  799. decoration elements.
  800. Grid cells, whether thay are in the header, body, or footer, have a basic
  801. [literal]#++v-grid-cell++# style. Cells in a frozen column additionally have a
  802. [literal]#++frozen++# style. Rows have [literal]#++v-grid-row++# style, and
  803. every other row has additionally a [literal]#++v-grid-row-stripe++# style.
  804. The focused row has additionally [literal]#++v-grid-row-focused++# style and
  805. focused cell [literal]#++v-grid-cell-focused++#. By default, cell focus is
  806. visible, with the border stylable with [parameter]#$v-grid-cell-focused-border#
  807. parameter in Sass. Row focus has no visible styling, but can be made visible
  808. with the [parameter]#$v-grid-row-focused-background-color# parameter or with a
  809. custom style rule.
  810. In editing mode, a [literal]#++v-grid-editor++# overlay is placed on the row
  811. under editing. In addition to the editor field cells, it has an error message
  812. element, as well as the buttons.
  813. ((()))