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 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. ---
  2. title: Grid
  3. order: 24
  4. layout: page
  5. ---
  6. [[components.grid]]
  7. = 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. [[components.grid.data]]
  34. == Binding to Data
  35. [classname]#Grid# is normally used by binding it to a data provider,
  36. described in
  37. <<dummy/../../../framework/datamodel/datamodel-providers.asciidoc#datamodel.dataproviders,"Showing Many Items in a Listing">>.
  38. By default, it is bound to List of items. You can set the items with the
  39. [methodname]#setItems()# method.
  40. For example, if you have a list of beans, you show them in a [classname]#Grid# as follows
  41. [source, java]
  42. ----
  43. // Have some data
  44. List<Person> people = Arrays.asList(
  45. new Person("Nicolaus Copernicus", 1543),
  46. new Person("Galileo Galilei", 1564),
  47. new Person("Johannes Kepler", 1571));
  48. // Create a grid bound to the list
  49. Grid<Person> grid = new Grid<>();
  50. grid.setItems(people);
  51. grid.addColumn(Person::getName).setCaption("Name");
  52. grid.addColumn(Person::getBirthYear).setCaption("Year of birth");
  53. layout.addComponent(grid);
  54. ----
  55. [[components.grid.selection]]
  56. == Handling Selection Changes
  57. Selection in [classname]#Grid# is handled a bit differently from other selection
  58. components, as it is not a [classname]#HasValue#. Grid supports
  59. single, multiple, or no-selection, each defined by a specific selection model. Each
  60. selection model has a specific API depending on the type of the selection.
  61. For basic usage, switching between the built-in selection models is possible by using the
  62. [method]#setSelectionMode(SelectionMode)#. Possible options are [literal]#++SINGLE++# (default),
  63. [literal]#++MULTI++#, or [literal]#++NONE++#.
  64. Listening to selection changes in any selection model is possible with a [classname]#SelectionListener#,
  65. which provides a generic [classname]#SelectionEvent# which for getting the selected value or values.
  66. Note that the listener is actually attached to the selection model and not the grid,
  67. and will stop getting any events if the selection mode is changed.
  68. [source, java]
  69. ----
  70. Grid<Person> grid = new Grid<>();
  71. // switch to multiselect mode
  72. grid.setSelectionMode(SelectionMode.MULTI);
  73. grid.addSelectionListener(event -> {
  74. Set<Person> selected = event.getAllSelectedItems();
  75. Notification.show(selected.size() + " items selected");
  76. });
  77. ----
  78. Programmatically selecting the value is possible via [methodname]#select(T)#.
  79. In multiselect mode, this will add the given item to the selection.
  80. [source, java]
  81. ----
  82. // in single-select, only one item is selected
  83. grid.select(defaultPerson);
  84. // switch to multi select, clears selection
  85. grid.setSelectionMode(SelectionMode.MULTI);
  86. // Select items 2-4
  87. people.subList(2,3).forEach(grid::select);
  88. ----
  89. The current selection can be obtained from the [classname]#Grid# by
  90. [methodname]#getSelectedItems()#, and the returned [classname]#Set# contains either
  91. only one item (in single-selection mode) or several items (in multi-selection mode).
  92. [WARNING]
  93. ====
  94. If you change selection mode for a grid, it will clear the selection
  95. and fire a selection event. To keep the previous selection you must
  96. reset the selection afterwards using the [methodname]#select()# method.
  97. ====
  98. [WARNING]
  99. ====
  100. If you change the grid's items with [methodname]#setItems()# or the used
  101. [classname]#DataProvider#, it will clear the selection and fire a selection event.
  102. To keep the previous selection you must reset the selection afterwards
  103. using the [methodname]#select()# method.
  104. ====
  105. [[components.grid.selection.mode]]
  106. === Selection Models
  107. For more control over the selection, you can access the used selection model with
  108. [methodname]#getSelectionModel()#. The return type is [classname]#GridSelectionModel#
  109. which has generic selection model API, but you can cast that to the specific selection model type,
  110. typically either [classname]#SingleSelectionModel# or [classname]#MultiSelectionModel#.
  111. The selection model is also returned by the [methodname]#setSelectionMode(SelectionMode)# method.
  112. [source, java]
  113. ----
  114. // the default selection model
  115. SingleSelectionModel<Person> defaultModel =
  116. (SingleSelectionModel<Person>) grid.getSelectionModel();
  117. // Use multi-selection mode
  118. MultiSelectionModel<Person> selectionModel =
  119. (MultiSelectionModel<Person>) grid.setSelectionMode(SelectionMode.MULTI);
  120. ----
  121. ==== Single Selection Model
  122. By obtaining a reference to the [classname]#SingleSelectionModel#,
  123. you can access more fine grained API for the single-select case.
  124. The [methodname]#addSingleSelect(SingleSelectionListener)# method provides access to
  125. [classname]#SingleSelectionEvent#, which has some extra API for more convenience.
  126. In single-select mode, it is possible to control whether the empty (null) selection is allowed.
  127. By default it is enabled, but can be disabled with [methodname]#setDeselectAllowed()#.
  128. [source, java]
  129. ----
  130. // preselect value
  131. grid.select(defaultItem);
  132. SingleSelectionModel<Person> singleSelect =
  133. (SingleSelectionModel<Person>) grid.getSelectionModel();
  134. // disallow empty selection
  135. singleSelect.setDeselectAllowed(false);
  136. ----
  137. [[components.grid.selection.multi]]
  138. === Multi-Selection Model
  139. In the multi-selection mode, a user can select multiple items by clicking on
  140. the checkboxes in the leftmost column, or by using the kbd:[Space] to select/deselect the currently focused row.
  141. Space bar is the default key for toggling the selection, but it can be customized.
  142. [[figure.components.grid.selection.multi]]
  143. .Multiple Selection in [classname]#Grid#
  144. image::img/grid-selection-multi.png[width=50%, scaledwidth=75%]
  145. By obtaining a reference to the [classname]#MultiSelectionModel#,
  146. you can access more fine grained API for the multi-select case.
  147. The [classname]#MultiSelectionModel# provides [methodname]#addMultiSelectionListener(MultiSelectionListener)#
  148. access to [classname]#MultiSelectionEvent#, which allows to easily access differences in the selection change.
  149. [source, java]
  150. ----
  151. // Grid in multi-selection mode
  152. Grid<Person> grid = new Grid<>()
  153. grid.setItems(people);
  154. MultiSelectionModel<Person> selectionModel
  155. = (MultiSelectionModel<Person>) grid.setSelectionMode(SelectionMode.MULTI);
  156. selectionModel.selectAll();
  157. selectionModel.addMultiSelectionListener(event -> {
  158. Notification.show(selection.getAddedSelection().size()
  159. + " items added, "
  160. + selection.getRemovedSelection().size()
  161. + " removed.");
  162. // Allow deleting only if there's any selected
  163. deleteSelected.setEnabled(
  164. event.getNewSelection().size() > 0);
  165. });
  166. ----
  167. [[components.grid.selection.clicks]]
  168. === Focus and Clicks
  169. In addition to selecting rows, you can focus individual cells. The focus can be
  170. moved with arrow keys and, if editing is enabled, pressing kbd:[Enter] opens the
  171. editor. Normally, pressing kbd:[Tab] or kbd:[Shift+Tab] moves the focus to another component,
  172. as usual.
  173. When editing or in unbuffered mode, kbd:[Tab] or kbd:[Shift+Tab] moves the focus to the next or
  174. previous cell. The focus moves from the last cell of a row forward to the
  175. beginning of the next row, and likewise, from the first cell backward to the
  176. end of the previous row. Note that you can extend [classname]#DefaultEditorEventHandler#
  177. to change this behavior.
  178. With the mouse, you can focus a cell by clicking on it. The clicks can be handled
  179. with an [interfacename]#ItemClickListener#. The [classname]#ItemClickEvent#
  180. object contains various information, most importantly the ID of the clicked row
  181. and column.
  182. [source, java]
  183. ----
  184. grid.addItemClickListener(event ->
  185. Notification.show("Value: " + event.getItem()));
  186. ----
  187. The clicked grid cell is also automatically focused.
  188. The focus indication is themed so that the focused cell has a visible focus
  189. indicator style by default, while the row does not. You can enable row focus, as
  190. well as disable cell focus, in a custom theme. See <<components.grid.css>>.
  191. [[components.grid.right.clicks]]
  192. === Right-clicks
  193. Right-clicks are supported similar way via `addContextClickListener()` method
  194. [source, java]
  195. ----
  196. grid.addContextClickListener(event -> Notification.show(
  197. ((GridContextClickEvent<Person>)event).getItem() + " Clicked")
  198. );
  199. ----
  200. [[components.grid.columns]]
  201. == Configuring Columns
  202. The [methodname]#addColumn()# method can be used to add columns to [classname]#Grid#.
  203. Column configuration is defined in [classname]#Grid.Column# objects, which are returned by `addColumn` and can also be obtained from the grid with [methodname]#getColumns()#.
  204. The setter methods in [classname]#Column# have _fluent API_, so you can easily chain the configuration calls for columns if you want to.
  205. [source, java]
  206. ----
  207. grid.addColumn(Person::getBirthDate, new DateRenderer())
  208. .setCaption("Birth Date")
  209. .setWidth("100px")
  210. .setResizable(false);
  211. ----
  212. In the following, we describe the basic column configuration.
  213. [[components.grid.columns.automatic]]
  214. === Automatically Adding Columns
  215. You can configure `Grid` to automatically add columns based on the properties in a bean.
  216. To do this, you need to pass the `Class` of the bean type to the constructor when creating a grid.
  217. You can then further configure the columns based on the bean property name.
  218. [source, java]
  219. ----
  220. Grid<Person> grid = new Grid<>(Person.class);
  221. grid.getColumn("birthDate").setWidth("100px");
  222. grid.setItems(people);
  223. ----
  224. [[components.grid.columns.order]]
  225. === Column Order
  226. You can set the order of columns with [methodname]#setColumnOrder()# for the
  227. grid. Columns that are not given for the method are placed after the specified
  228. columns in their natural order.
  229. [source, java]
  230. ----
  231. grid.setColumnOrder(firstnameColumn, lastnameColumn,
  232. bornColumn, birthplaceColumn,
  233. diedColumn);
  234. ----
  235. Note that the method can not be used to hide columns. You can hide columns with
  236. the [methodname]#removeColumn()#, as described later.
  237. [[components.grid.columns.removing]]
  238. === Hiding and Removing Columns
  239. Columns can be hidden by calling [methodname]#setHidden()# in [classname]#Column#.
  240. Furthermore, you can set the columns user hidable using method
  241. [methodname]#setHidable()#.
  242. Columns can be removed with [methodname]#removeColumn()# and
  243. [methodname]#removeAllColumns()#. To restore a previously removed column,
  244. you can call [methodname]#addColumn()#.
  245. [[components.grid.columns.captions]]
  246. === Column Captions
  247. Column captions are displayed in the grid header. You can set the header caption
  248. explicitly through the column object with [methodname]#setCaption()#.
  249. [source, java]
  250. ----
  251. Column<Date> bornColumn = grid.addColumn(Person::getBirthDate);
  252. bornColumn.setCaption("Born date");
  253. ----
  254. This is equivalent to setting it with [methodname]#setText()# for the header
  255. cell; the [classname]#HeaderCell# also allows setting the caption in HTML or as
  256. a component, as well as styling it, as described later in
  257. <<components.grid.headerfooter>>.
  258. [[components.grid.columns.width]]
  259. === Column Widths
  260. Columns have by default undefined width, which causes automatic sizing based on
  261. the widths of the displayed data. You can set column widths explicitly by pixel
  262. value with [methodname]#setWidth()#, or relatively using expand ratios with
  263. [methodname]#setExpandRatio()#.
  264. When using expand ratios, the columns with a non-zero expand ratio use the extra
  265. space remaining from other columns, in proportion to the defined ratios. Do note
  266. that the minimum width of an expanded column by default is based on the contents
  267. of the column (the initially rendered rows). To allow the column to become
  268. narrower than this, use [methodname]#setMinimumWidthFromContent(false)#
  269. (introduced in 8.1).
  270. You can specify minimum and maximum widths for the expanding columns with
  271. [methodname]#setMinimumWidth()# and [methodname]#setMaximumWidth()#,
  272. respectively.
  273. The user can resize columns by dragging their separators with the mouse. When resized manually,
  274. all the columns widths are set to explicit pixel values, even if they had
  275. relative values before.
  276. [[components.grid.columns.frozen]]
  277. === Frozen Columns
  278. You can set the number of columns to be frozen with
  279. [methodname]#setFrozenColumnCount()#, so that they are not scrolled off when
  280. scrolling horizontally.
  281. [source, java]
  282. ----
  283. grid.setFrozenColumnCount(2);
  284. ----
  285. Setting the count to [parameter]#0# disables frozen data columns; setting it to
  286. [parameter]#-1# also disables the selection column in multi-selection mode.
  287. [[components.grid.generatedcolumns]]
  288. == Generating Columns
  289. Columns with values computed from other columns can be simply added by using
  290. lambdas:
  291. [source, java]
  292. ----
  293. // Add generated full name column
  294. Column<String> fullNameColumn = grid.addColumn(person ->
  295. person.getFirstName() + " " + person.getLastName());
  296. fullNameColumn.setCaption("Full name");
  297. ----
  298. [[components.grid.renderer]]
  299. == Column Renderers
  300. A __renderer__ is a feature that draws the client-side representation of a data
  301. value. This allows having images, HTML, and buttons in grid cells.
  302. [[figure.components.grid.renderer]]
  303. .Column renderers: image, date, HTML, and button
  304. image::img/grid-renderers.png[width=75%, scaledwidth=100%]
  305. Renderers implement the [interfacename]#Renderer# interface.
  306. Renderers require a specific data type for the column.
  307. You set the column renderer in the [classname]#Grid.Column# object as follows:
  308. [source, java]
  309. ----
  310. // the type of birthYear is a number
  311. Column<Person, Integer> bornColumn = grid.addColumn(Person::getBirthYear,
  312. new NumberRenderer("born in %d AD"));
  313. ----
  314. Changing the renderer during runtime is also possible, but for type safety
  315. you should store the column reference with data types for doing this.
  316. When you change the renderer, the content of Grid is refreshed.
  317. [source, java]
  318. ----
  319. Column<Person, Integer> ageColumn = grid.addColumn(Person::getBirthYear);
  320. // The default renderer is TextRenderer
  321. addComponent(new Button("Change renderer",
  322. clickEvent -> ageColumn.setRenderer(new NumberRenderer())
  323. ));
  324. ----
  325. The following renderers are available, as defined in the server-side
  326. [package]#com.vaadin.ui.renderers# package:
  327. [classname]#TextRenderer#:: The default renderer, displays plain text as is. Any HTML markup is quoted.
  328. [classname]#ButtonRenderer#:: Renders the data value as the caption of a button. A [interfacename]#RendererClickListener# can be given to handle the button clicks.
  329. +
  330. Typically, a button renderer is used to display buttons for operating on a data
  331. item, such as edit, view, delete, etc. It is not meaningful to store the button
  332. captions in the data source, rather you want to generate them, and they are
  333. usually all identical.
  334. +
  335. [source, java]
  336. ----
  337. List<Person> people = new ArrayList<>();
  338. people.add(new Person("Nicolaus Copernicus", 1473));
  339. people.add(new Person("Galileo Galilei", 1564));
  340. people.add(new Person("Johannes Kepler", 1571));
  341. // Create a grid
  342. Grid<Person> grid = new Grid<>(people);
  343. // Render a button that deletes the data row (item)
  344. grid.addColumn(person -> "Delete",
  345. new ButtonRenderer(clickEvent -> {
  346. people.remove(clickEvent.getItem());
  347. grid.setItems(people);
  348. }));
  349. ----
  350. [classname]#ImageRenderer#:: Renders the cell as an image.
  351. The column type must be a [interfacename]#Resource#, as described in
  352. <<dummy/../../../framework/application/application-resources#application.resources,"Images and Other Resources">>; only [classname]#ThemeResource# and
  353. [classname]#ExternalResource# are currently supported for images in
  354. [classname]#Grid#.
  355. +
  356. [source, java]
  357. ----
  358. Column<Person, ThemeResource> imageColumn = grid.addColumn(
  359. p -> new ThemeResource("img/"+p.getLastname()+".jpg"),
  360. new ImageRenderer());
  361. ----
  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. +
  367. [source, java]
  368. ----
  369. Column<Person, Date> bornColumn = grid.addColumn(Person::getBirthDate,
  370. new DateRenderer("%1$tB %1$te, %1$tY",
  371. Locale.ENGLISH));
  372. ----
  373. +
  374. Optionally, a locale can be given. Otherwise, the default locale (in the
  375. component tree) is used.
  376. [classname]#HTMLRenderer#:: Renders the cell as HTML.
  377. This allows formatting the cell content, as well as using HTML features such as hyperlinks.
  378. +
  379. Set the renderer in the [classname]#Grid.Column# object:
  380. +
  381. [source, java]
  382. ----
  383. Column<Person, String> htmlColumn = grid.addColumn(person ->
  384. "<a href='" + person.getDetailsUrl() + "' target='_top'>info</a>",
  385. new HtmlRenderer());
  386. ----
  387. [classname]#NumberRenderer#:: Formats column values with a numeric type extending [classname]#Number#:
  388. [classname]#Integer#, [classname]#Double#, etc. The format can be specified
  389. either by the subclasses of [classname]#java.text.NumberFormat#, namely
  390. [classname]#DecimalFormat# and [classname]#ChoiceFormat#, or by
  391. [methodname]#String.format()#.
  392. +
  393. For example:
  394. +
  395. [source, java]
  396. ----
  397. // Use decimal format
  398. Column<Integer> birthYear = grid.addColumn(Person::getBirthYear,
  399. new NumberRenderer(new DecimalFormat("in #### AD")));
  400. ----
  401. [classname]#ProgressBarRenderer#:: Renders a progress bar in a column with a [classname]#Double# type. The value
  402. must be between 0.0 and 1.0.
  403. [classname]#LocalDateRenderer#::
  404. Formats a column with the [classname]#LocalDate# type.
  405. The renderer can be constructed with a [classname]#DateTimeFormatter#, or with a custom pattern string.
  406. The locale is either given explicitly with the pattern, resolved from the given [classname]#DateTimeFormatter# or from the grid the renderer is attached to, if neither of the previous are given.
  407. For the pattern string syntax, refer to the following documentation: link:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns[docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns].
  408. Note we should use `SerializableProvider&lt;DateTimeFormatter&gt;` or lambda in the first case, because
  409. `DateTimeFormatter` is not serializable, and that may lead to problems in certain cases, for instance in a cluster environment.
  410. +
  411. [source, java]
  412. ----
  413. LocalDateRenderer renderer = new LocalDateRenderer(() -> DateTimeFormatter
  414. .ofLocalizedDate(FormatStyle.LONG)
  415. .withLocale(Locale.ENGLISH));
  416. Column<Person, LocalDate> bornColumn =
  417. grid.addColumn(
  418. Person::getBirthDate,
  419. renderer);
  420. // Alternatively, with a custom pattern:
  421. Column<Person, LocalDate> bornColumn =
  422. grid.addColumn(
  423. Person::getBirthDate,
  424. new LocalDateRenderer("yyyy MM dd"));
  425. ----
  426. [classname]#LocalDateTimeRenderer#::
  427. Otherwise the same as [classname]#LocalDateRenderer#, except for the [classname]#LocalDateTime# type.
  428. +
  429. [source, java]
  430. ----
  431. LocalDateTimeRenderer renderer = new LocalDateTimeRenderer(
  432. () -> DateTimeFormatter
  433. .ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT)
  434. .withLocale(Locale.ENGLISH));
  435. Column<Person, LocalDateTime> bornColumn =
  436. grid.addColumn(Person::getBirthDateAndTime, renderer);
  437. // Alternatively, with a custom pattern:
  438. Column<Person, LocalDateTime> bornColumn =
  439. grid.addColumn(
  440. Person::getBirthDateAndTime,
  441. new LocalDateTimeRenderer("yyyy.MM.dd 'at' hh:mm"));
  442. ----
  443. [classname]#ComponentRenderer#:: Renders a Vaadin [classname]#Component# in a column. Since components
  444. are quite complex, the [classname]#ComponentRenderer# comes with possible performance issues.
  445. To use it efficiently you should use as few nested components as possible. If the components used are
  446. of a different size than the default row height, [methodname]#Grid.setBodyRowHeight()# can be used to adjust
  447. the height of all rows in the Grid.
  448. +
  449. Use [classname]#Button# in [classname]#Grid#:
  450. +
  451. ----
  452. grid.addComponentColumn(person -> {
  453. Button button = new Button("Click me!");
  454. button.addClickListener(click ->
  455. Notification.show("Clicked: " + person.toString()));
  456. return button;
  457. });
  458. // make sure the buttons fit in the cells of the Grid
  459. grid.setBodyRowHeight(40);
  460. ----
  461. +
  462. Components will occasionally be generated again during runtime. If you have a state in your
  463. component and not in the data object, you need to handle storing it yourself. Below is a simple
  464. example on how to achieve this.
  465. +
  466. Store a [classname]#TextField# with changed value.
  467. +
  468. ----
  469. Map<Person, TextField> textFields = new HashMap<>();
  470. grid.addColumn(person -> {
  471. // Check for existing text field
  472. if (textFields.containsKey(person)) {
  473. return textFields.get(person);
  474. }
  475. // Create a new one
  476. TextField textField = new TextField();
  477. textField.setValue(person.getLastname());
  478. // Store the text field when user updates the value
  479. textField.addValueChangeListener(change ->
  480. textFields.put(person, textField));
  481. return textField;
  482. }, new ComponentRenderer());
  483. ----
  484. [classname]#Components# in [classname]#Grid# [classname]#ComponentRenderer# are wrapped in a [literal]#++div++# with the style name [literal]#++component-wrap++#. This can be used to style the alignment and size of the [classname]#Component#.
  485. [[components.grid.renderer.custom]]
  486. === Custom Renderers
  487. Renderers are component extensions that require a client-side counterpart. See
  488. <<dummy/../../../framework/clientsidewidgets/clientsidewidgets-grid#clientsidewidgets.grid.renderers,"Renderers">>
  489. for information on implementing custom renderers.
  490. [[components.grid.headerfooter]]
  491. == Header and Footer
  492. A grid by default has a header, which displays column names, and can have a
  493. footer. Both can have multiple rows and neighbouring header row cells can be
  494. joined to feature column groups.
  495. [[components.grid.headerfooter.adding]]
  496. === Adding and Removing Header and Footer Rows
  497. A new header row is added with [methodname]#prependHeaderRow()#, which adds it
  498. at the top of the header, [methodname]#appendHeaderRow()#, which adds it at the
  499. bottom of the header, or with [methodname]#addHeaderRowAt()#, which inserts it
  500. at the specified 0-base index. All of the methods return a
  501. [classname]#HeaderRow# object, which you can use to work on the header further.
  502. [source, java]
  503. ----
  504. // Group headers by joining the cells
  505. HeaderRow groupingHeader = grid.prependHeaderRow();
  506. ...
  507. // Create a header row to hold column filters
  508. HeaderRow filterRow = grid.appendHeaderRow();
  509. ...
  510. ----
  511. Similarly, you can add footer rows with [methodname]#appendFooterRow()#,
  512. [methodname]#prependFooterRow()#, and [methodname]#addFooterRowAt()#.
  513. [[components.grid.headerfooter.joining]]
  514. === Joining Header and Footer Cells
  515. You can join two or more header or footer cells with the [methodname]#join()#
  516. method. For header cells, the intention is usually to create column grouping,
  517. while for footer cells, you typically calculate sums or averages.
  518. [source, java]
  519. ----
  520. // Group headers by joining the cells
  521. HeaderRow groupingHeader = grid.prependHeaderRow();
  522. HeaderCell namesCell = groupingHeader.join(
  523. groupingHeader.getCell("firstname"),
  524. groupingHeader.getCell("lastname")).setText("Person");
  525. HeaderCell yearsCell = groupingHeader.join(
  526. groupingHeader.getCell("born"),
  527. groupingHeader.getCell("died"),
  528. groupingHeader.getCell("lived")).setText("Dates of Life");
  529. ----
  530. [[components.grid.headerfooter.content]]
  531. === Text and HTML Content
  532. You can set the header caption with [methodname]#setText()#, in which case any
  533. HTML formatting characters are quoted to ensure security.
  534. [source, java]
  535. ----
  536. HeaderRow mainHeader = grid.getDefaultHeaderRow();
  537. mainHeader.getCell("firstname").setText("First Name");
  538. mainHeader.getCell("lastname").setText("Last Name");
  539. mainHeader.getCell("born").setText("Born In");
  540. mainHeader.getCell("died").setText("Died In");
  541. mainHeader.getCell("lived").setText("Lived For");
  542. ----
  543. To use raw HTML in the captions, you can use [methodname]#setHtml()#.
  544. [source, java]
  545. ----
  546. namesCell.setHtml("<b>Names</b>");
  547. yearsCell.setHtml("<b>Years</b>");
  548. ----
  549. [[components.grid.headerfooter.components]]
  550. === Components in Header or Footer
  551. You can set a component in a header or footer cell with
  552. [methodname]#setComponent()#. Often, this feature is used to allow filtering.
  553. ////
  554. // commented out until filtering is sorted for 8
  555. [[components.grid.filtering]]
  556. == Filtering
  557. The ability to include components in the grid header can be used to create
  558. filters for the grid data. Filtering is done in the container data source, so
  559. the container must be of type that implements
  560. [interfacename]#Container.Filterable#.
  561. [[figure.components.grid.filtering]]
  562. .Filtering Grid
  563. image::img/grid-filtering.png[width=50%, scaledwidth=80%]
  564. The filtering illustrated in <<figure.components.grid.filtering>> can be created
  565. as follows:
  566. [source, java]
  567. ----
  568. // Have a list of persons
  569. List<Person> people = getPeople();
  570. // Create a grid bound to it
  571. Grid<Person> grid = new Grid<>();
  572. grid.setItems(people);
  573. grid.setSelectionMode(SelectionMode.NONE);
  574. grid.setWidth("500px");
  575. grid.setHeight("300px");
  576. // Create a header row to hold column filters
  577. HeaderRow filterRow = grid.appendHeaderRow();
  578. // Set up a filter for all columns
  579. for (Column<?> col: grid.getColumns()) {
  580. HeaderCell cell = filterRow.getCell(col);
  581. // Have an input field to use for filter
  582. TextField filterField = new TextField();
  583. // Update filter When the filter input is changed
  584. filterField.addValueChangeListener(event -> {
  585. // Filter the list of items
  586. List<String> filteredList =
  587. // XXX shouldn't use Lists here since it's from Guava instead of the vanilla JRE. Revise when updating this code example for the new filtering API!
  588. Lists.newArrayList(personList.filter(persons,
  589. Predicates.containsPattern(event.getValue())));
  590. // Apply filtered data
  591. grid.setItems(filteredList);
  592. });
  593. cell.setComponent(filterField);
  594. }
  595. ----
  596. ////
  597. [[components.grid.sorting]]
  598. == Sorting
  599. A user can sort the data in a grid on a column by clicking the column header.
  600. Clicking another time on the current sort column reverses the sort direction.
  601. Clicking on other column headers while keeping the Shift key pressed adds a
  602. secondary or more sort criteria.
  603. [[figure.components.grid.sorting]]
  604. .Sorting Grid on Multiple Columns
  605. image::img/grid-sorting.png[width=50%, scaledwidth=75%]
  606. Defining sort criteria programmatically can be done with the various
  607. alternatives of the [methodname]#sort()# method. You can sort on a specific
  608. column with [methodname]#sort(Column column)#, which defaults to ascending
  609. sorting order, or [methodname]#sort(Column column, SortDirection
  610. direction)#, which allows specifying the sort direction.
  611. [source, java]
  612. ----
  613. grid.sort(nameColumn, SortDirection.DESCENDING);
  614. ----
  615. To sort by multiple columns, you need to use the fluid sort builder API
  616. [classname]#GridSortOrderBuilder#, which allows you to easily construct sorting information to be passed to grid's [methodname]#setSortOrder()# method.
  617. A sort builder is created with the static methods [methodname]#asc()# and [methodname]#desc()#,
  618. and additional sorting information can by chained with [methodname]#thenAsc()# and [methodname]#thenDesc()#.
  619. [source, java]
  620. ----
  621. // Sort first by city (ascending) and then by name (descending)
  622. grid.setSortOrder(GridSortOrder.asc(cityColumn).thenDesc(nameColumn))
  623. ----
  624. [[components.grid.editing]]
  625. == Editing Items Inside Grid
  626. Grid supports line-based editing, where double-clicking a row opens the row
  627. editor. In the editor, the input fields can be edited, as well as navigated with
  628. kbd:[Tab] and kbd:[Shift+Tab] keys. If validation fails, an error is displayed and the user
  629. can correct the inputs.
  630. The [classname]#Editor# is accessible via [methodname]#getEditor()#, and to enable editing, you need to call [methodname]#setEnabled(true)# on it.
  631. The editor is based on [classname]#Binder# which is used to bind the data to the editor.
  632. See <<dummy/../../../framework/datamodel/datamodel-forms.asciidoc#datamodel.forms.beans,"Binding Beans to Forms">> for more information on setting up field components and validation by using [classname]#Binder#.
  633. For each column that should be editable, a binding should be created in the editor binder and then the column is configured to use that binding.
  634. For simple cases where no conversion or validation is needed, it is also possible to directly use `setEditorComponent` on a `Column` to only define the editor component and a setter that updates the row object when saving.
  635. [source, java]
  636. ----
  637. List<Todo> items = Arrays.asList(new Todo("Done task", true),
  638. new Todo("Not done", false));
  639. Grid<Todo> grid = new Grid<>();
  640. TextField taskField = new TextField();
  641. CheckBox doneField = new CheckBox();
  642. Binder<Todo> binder = grid.getEditor().getBinder();
  643. Binding<Todo, Boolean> doneBinding = binder.bind(
  644. doneField, Todo::isDone, Todo::setDone);
  645. Column<Todo, String> column = grid.addColumn(
  646. todo -> String.valueOf(todo.isDone()));
  647. column.setWidth(75);
  648. column.setEditorBinding(doneBinding);
  649. grid.addColumn(Todo::getTask).setEditorComponent(
  650. taskField, Todo::setTask).setExpandRatio(1);
  651. grid.getEditor().setEnabled(true);
  652. ----
  653. [[components.grid.editing.buffered]]
  654. === Buffered / Unbuffered Mode
  655. Grid supports two editor modes - buffered and unbuffered. The default mode is
  656. buffered. The mode can be changed with [methodname]#setBuffered(false)#.
  657. In the buffered mode, editor has two buttons visible: a [guibutton]#Save# button that commits
  658. the modifications to the bean and closes the editor and a [guibutton]#Cancel# button
  659. discards the changes and exits the editor.
  660. Editor in buffered mode is illustrated in <<figure.components.grid.editing>>.
  661. [[figure.components.grid.editing]]
  662. .Editing a Grid Row
  663. image::img/grid-editor-basic.png[width=50%, scaledwidth=75%]
  664. In the unbuffered mode, the editor has no buttons and all changed data is committed directly
  665. to the data provider. If another row is clicked, the editor for the current row is closed and
  666. a row editor for the clicked row is opened.
  667. [[components.grid.editing.captions]]
  668. === Customizing Editor Buttons
  669. In the buffered mode, the editor has two buttons: [guibutton]#Save# and [guibutton]#Cancel#. You can
  670. set their captions with [methodname]#setEditorSaveCaption()# and
  671. [methodname]#setEditorCancelCaption()#, respectively.
  672. In the following example, we demonstrate one way to translate the captions:
  673. [source, java]
  674. ----
  675. // Localize the editor button captions
  676. grid.getEditor().setSaveCaption("Tallenna");
  677. grid.getEditor().setCancelCaption("Peruuta"));
  678. ----
  679. [[components.grid.editing.validation]]
  680. === Handling Validation Errors
  681. The input fields are validated when the value is updated. The default
  682. error handler displays error indicators in the invalid fields, as well as the
  683. first error in the editor.
  684. [[figure.components.grid.errors]]
  685. .Editing a Grid Row
  686. image::img/grid-editor-errors.png[width=50%, scaledwidth=75%]
  687. You can modify the error message by implementing a custom
  688. [interfacename]#EditorErrorGenerator# with for the [classname]#Editor#.
  689. [[components.grid.presentation.provider]]
  690. === Presentation Value Providers
  691. By default, a renderer displays the column value. If you want to edit an
  692. internal value (such as an address object) but show a simpler representation
  693. when not editing a row, a presentation value provider can be used.
  694. A presentation value provider converts the value of a cell (obtained with a
  695. value provider, and used by the editor) to a different representation to be
  696. shown by renderers when the cell is not being edited. A custom renderer can
  697. optionally be used for the presentation values.
  698. In the following example, we demonstrate one way to use a simplified
  699. presentation of an address column while allowing editing the full address:
  700. [source, java]
  701. ----
  702. Column<Person, Address> column = grid.addColumn(Person::getAddress);
  703. // alternatively, the presentation provider can be given as an extra parameter
  704. // to addColumn()
  705. column.setRenderer(
  706. address -> address.getCity() + " " + address.getCountry(),
  707. new TextRenderer());
  708. column.setCaption("Address");
  709. column.setEditorComponent(new AddressField(), Person::setAddress);
  710. ----
  711. ////
  712. // Not supported in 8
  713. [[components.grid.scrolling]]
  714. == Programmatic Scrolling
  715. You can scroll to first item with [methodname]#scrollToStart()#, to end with
  716. [methodname]#scrollToEnd()#, or to a specific row with [methodname]#scrollTo()#.
  717. ////
  718. == Drag and Drop of Rows
  719. Please refer to the
  720. <<dummy/../../../framework/advanced/advanced-dragndrop#advanced.dragndrop.grid,"Drag and Drop Rows in Grid">> documentation.
  721. [[advanced.dragndrop.grid]]
  722. [[components.grid.stylegeneration]]
  723. == Generating Row or Cell Styles
  724. You can style entire rows or individual cells with a
  725. [interfacename]#StyleGenerator#, typically used through Java lambdas.
  726. [[components.grid.stylegeneration.row]]
  727. === Generating Row Styles
  728. The easiest way to style rows is to make a lambda and set it with
  729. [methodname]#setStyleGenerator()# to a grid.
  730. The lambda gets a data item, and should return a style name or [parameter]#null# if
  731. no style is generated.
  732. For example, to add a style names to rows having certain values in one
  733. property of an item, you can style them as follows:
  734. [source, java]
  735. ----
  736. grid.setStyleGenerator(person -> {
  737. // Style based on alive status
  738. person.isAlive() ? null : "dead";
  739. });
  740. ----
  741. You could then style the rows with CSS as follows:
  742. [source, css]
  743. ----
  744. .v-grid-row.dead {
  745. color: gray;
  746. }
  747. ----
  748. [[components.grid.stylegeneration.cell]]
  749. === Generating Cell Styles
  750. You set a [interfacename]#StyleGenerator# to a grid with
  751. [methodname]#setStyleGenerator()#. The [methodname]#getStyle()# method gets
  752. a [classname]#CellReference#, which contains various information about the cell
  753. and a reference to the grid, and should return a style name or [parameter]#null#
  754. if no style is generated.
  755. For example, to add a style name to a specific column, you can match on
  756. the column as follows:
  757. [source, java]
  758. ----
  759. // Static style based on column
  760. bornColumn.setStyleGenerator(person -> "rightalign");
  761. ----
  762. You could then style the cells with a CSS rule as follows:
  763. [source, css]
  764. ----
  765. .v-grid-cell.rightalign {
  766. text-align: right;
  767. }
  768. ----
  769. [[components.grid.css]]
  770. == Styling with CSS
  771. [source, css]
  772. ----
  773. .v-grid {
  774. .v-grid-scroller, .v-grid-scroller-horizontal { }
  775. .v-grid-tablewrapper {
  776. .v-grid-header {
  777. .v-grid-row {
  778. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  779. }
  780. }
  781. .v-grid-body {
  782. .v-grid-row,
  783. .v-grid-row-stripe,
  784. .v-grid-row-has-data {
  785. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  786. }
  787. }
  788. .v-grid-footer {
  789. .v-grid-row {
  790. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  791. }
  792. }
  793. }
  794. .v-grid-header-deco { }
  795. .v-grid-footer-deco { }
  796. .v-grid-horizontal-scrollbar-deco { }
  797. .v-grid-editor {
  798. .v-grid-editor-cells { }
  799. .v-grid-editor-footer {
  800. .v-grid-editor-message { }
  801. .v-grid-editor-buttons {
  802. .v-grid-editor-save { }
  803. .v-grid-editor-cancel { }
  804. }
  805. }
  806. }
  807. }
  808. ----
  809. A [classname]#Grid# has an overall [literal]#++v-grid++# style. The actual grid
  810. has three parts: a header, a body, and a footer. The scrollbar is a custom
  811. element with [literal]#++v-grid-scroller++# style. In addition, there are some
  812. decoration elements.
  813. Grid cells, whether thay are in the header, body, or footer, have a basic
  814. [literal]#++v-grid-cell++# style. Cells in a frozen column additionally have a
  815. [literal]#++frozen++# style. Rows have [literal]#++v-grid-row++# style, and
  816. every other row has additionally a [literal]#++v-grid-row-stripe++# style.
  817. The focused row has additionally [literal]#++v-grid-row-focused++# style and
  818. focused cell [literal]#++v-grid-cell-focused++#. By default, cell focus is
  819. visible, with the border stylable with [parameter]#$v-grid-cell-focused-border#
  820. parameter in Sass. Row focus has no visible styling, but can be made visible
  821. with the [parameter]#$v-grid-row-focused-background-color# parameter or with a
  822. custom style rule.
  823. In editing mode, a [literal]#++v-grid-editor++# overlay is placed on the row
  824. under editing. In addition to the editor field cells, it has an error message
  825. element, as well as the buttons.
  826. ((()))