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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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 = 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.addCellClickListener(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.columns]]
  192. == Configuring Columns
  193. The [methodname]#addColumn()# method can be used to add columns to [classname]#Grid#.
  194. 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()#.
  195. The setter methods in [classname]#Column# have _fluent API_, so you can easily chain the configuration calls for columns if you want to.
  196. [source, java]
  197. ----
  198. grid.addColumn(Person:getBirthDate, new DateRenderer())
  199. .setCaption("Birth Date")
  200. .setWidth("100px")
  201. .setResizable(false);
  202. ----
  203. In the following, we describe the basic column configuration.
  204. [[components.grid.columns.automatic]]
  205. === Automatically Adding Columns
  206. You can configure `Grid` to automatically add columns based on the properties in a bean.
  207. To do this, you need to pass the `Class` of the bean type to the constructor when creating a grid.
  208. You can then further configure the columns based on the bean property name.
  209. [source, java]
  210. ----
  211. Grid<Person> grid = new Grid<>(Person.class);
  212. grid.getColumn("birthDate").setWidth("100px");
  213. grid.setItems(people);
  214. ----
  215. [[components.grid.columns.order]]
  216. === Column Order
  217. You can set the order of columns with [methodname]#setColumnOrder()# for the
  218. grid. Columns that are not given for the method are placed after the specified
  219. columns in their natural order.
  220. [source, java]
  221. ----
  222. grid.setColumnOrder(firstnameColumn, lastnameColumn,
  223. bornColumn, birthplaceColumn,
  224. diedColumn);
  225. ----
  226. Note that the method can not be used to hide columns. You can hide columns with
  227. the [methodname]#removeColumn()#, as described later.
  228. [[components.grid.columns.removing]]
  229. === Hiding and Removing Columns
  230. Columns can be hidden by calling [methodname]#setHidden()# in [classname]#Column#.
  231. Furthermore, you can set the columns user hideable using method
  232. [methodname]#setHideable()#.
  233. Columns can be removed with [methodname]#removeColumn()# and
  234. [methodname]#removeAllColumns()#. To restore a previously removed column,
  235. you can call [methodname]#addColumn()#.
  236. [[components.grid.columns.captions]]
  237. === Column Captions
  238. Column captions are displayed in the grid header. You can set the header caption
  239. explicitly through the column object with [methodname]#setCaption()#.
  240. [source, java]
  241. ----
  242. Column<Date> bornColumn = grid.addColumn(Person:getBirthDate);
  243. bornColumn.setCaption("Born date");
  244. ----
  245. This is equivalent to setting it with [methodname]#setText()# for the header
  246. cell; the [classname]#HeaderCell# also allows setting the caption in HTML or as
  247. a component, as well as styling it, as described later in
  248. <<components.grid.headerfooter>>.
  249. [[components.grid.columns.width]]
  250. === Column Widths
  251. Columns have by default undefined width, which causes automatic sizing based on
  252. the widths of the displayed data. You can set column widths explicitly by pixel
  253. value with [methodname]#setWidth()#, or relatively using expand ratios with
  254. [methodname]#setExpandRatio()#.
  255. When using expand ratios, the columns with a non-zero expand ratio use the extra
  256. space remaining from other columns, in proportion to the defined ratios.
  257. You can specify minimum and maximum widths for the expanding columns with
  258. [methodname]#setMinimumWidth()# and [methodname]#setMaximumWidth()#,
  259. respectively.
  260. The user can resize columns by dragging their separators with the mouse. When resized manually,
  261. all the columns widths are set to explicit pixel values, even if they had
  262. relative values before.
  263. [[components.grid.columns.frozen]]
  264. === Frozen Columns
  265. You can set the number of columns to be frozen with
  266. [methodname]#setFrozenColumnCount()#, so that they are not scrolled off when
  267. scrolling horizontally.
  268. [source, java]
  269. ----
  270. grid.setFrozenColumnCount(2);
  271. ----
  272. Setting the count to [parameter]#0# disables frozen data columns; setting it to
  273. [parameter]#-1# also disables the selection column in multi-selection mode.
  274. [[components.grid.generatedcolumns]]
  275. == Generating Columns
  276. Columns with values computed from other columns can be simply added by using
  277. lambdas:
  278. [source, java]
  279. ----
  280. // Add generated full name column
  281. Column<String> fullNameColumn = grid.addColumn(person ->
  282. person.getFirstName() + " " + person.getLastName());
  283. fullNameColumn.setCaption("Full name");
  284. ----
  285. [[components.grid.renderer]]
  286. == Column Renderers
  287. A __renderer__ is a feature that draws the client-side representation of a data
  288. value. This allows having images, HTML, and buttons in grid cells.
  289. [[figure.components.grid.renderer]]
  290. .Column renderers: image, date, HTML, and button
  291. image::img/grid-renderers.png[width=75%, scaledwidth=100%]
  292. Renderers implement the [interfacename]#Renderer# interface.
  293. Renderers require a specific data type for the column.
  294. You set the column renderer in the [classname]#Grid.Column# object as follows:
  295. [source, java]
  296. ----
  297. // the type of birthYear is a number
  298. Column<Integer> bornColumn = grid.addColumn(Person:getBirthYear,
  299. new NumberRenderer("born in %d AD"));
  300. ----
  301. The following renderers are available, as defined in the server-side
  302. [package]#com.vaadin.ui.renderers# package:
  303. [classname]#TextRenderer#:: The default renderer, displays plain text as is. Any HTML markup is quoted.
  304. [classname]#ButtonRenderer#:: Renders the data value as the caption of a button. A [interfacename]#RendererClickListener# can be given to handle the button clicks.
  305. +
  306. Typically, a button renderer is used to display buttons for operating on a data
  307. item, such as edit, view, delete, etc. It is not meaningful to store the button
  308. captions in the data source, rather you want to generate them, and they are
  309. usually all identical.
  310. +
  311. [source, java]
  312. ----
  313. List<Person> people = new ArrayList<>();
  314. people.add(new Person("Nicolaus Copernicus", 1473));
  315. people.add(new Person("Galileo Galilei", 1564));
  316. people.add(new Person("Johannes Kepler", 1571));
  317. // Create a grid
  318. Grid<Person> grid = new Grid<>(people);
  319. // Render a button that deletes the data row (item)
  320. grid.addColumn(person -> "Delete",
  321. new ButtonRenderer(clickEvent -> {
  322. people.remove(clickEvent.getValue());
  323. grid.setItems(people);
  324. }));
  325. ----
  326. [classname]#ImageRenderer#:: Renders the cell as an image.
  327. The column type must be a [interfacename]#Resource#, as described in
  328. <<dummy/../../../framework/application/application-resources#application.resources,"Images and Other Resources">>; only [classname]#ThemeResource# and
  329. [classname]#ExternalResource# are currently supported for images in
  330. [classname]#Grid#.
  331. +
  332. [source, java]
  333. ----
  334. Column<ThemeResource> imageColumn = grid.addColumn(
  335. p -> new ThemeResource("img/"+p.getLastname()+".jpg"),
  336. new ImageRenderer());
  337. ----
  338. [classname]#DateRenderer#:: Formats a column with a [classname]#Date# type using string formatter. The
  339. format string is same as for [methodname]#String.format()# in Java API. The date
  340. is passed in the parameter index 1, which can be omitted if there is only one
  341. format specifier, such as "[literal]#++%tF++#".
  342. +
  343. [source, java]
  344. ----
  345. Grid.Column<Date> bornColumn = grid.addColumn(person:getBirthDate,
  346. new DateRenderer("%1$tB %1$te, %1$tY",
  347. Locale.ENGLISH));
  348. ----
  349. +
  350. Optionally, a locale can be given. Otherwise, the default locale (in the
  351. component tree) is used.
  352. [classname]#HTMLRenderer#:: Renders the cell as HTML.
  353. This allows formatting the cell content, as well as using HTML features such as hyperlinks.
  354. +
  355. Set the renderer in the [classname]#Grid.Column# object:
  356. +
  357. [source, java]
  358. ----
  359. Column<String> htmlColumn grid.addColumn(person ->
  360. "<a href='" + person.getDetailsUrl() + "' target='_top'>info</a>",
  361. new HtmlRenderer());
  362. ----
  363. [classname]#NumberRenderer#:: Formats column values with a numeric type extending [classname]#Number#:
  364. [classname]#Integer#, [classname]#Double#, etc. The format can be specified
  365. either by the subclasses of [classname]#java.text.NumberFormat#, namely
  366. [classname]#DecimalFormat# and [classname]#ChoiceFormat#, or by
  367. [methodname]#String.format()#.
  368. +
  369. For example:
  370. +
  371. [source, java]
  372. ----
  373. // Use decimal format
  374. Column<Integer> birthYear = grid.addColumn(Person::getBirthYear,
  375. new NumberRenderer(new DecimalFormat("in #### AD")));
  376. ----
  377. [classname]#ProgressBarRenderer#:: Renders a progress bar in a column with a [classname]#Double# type. The value
  378. must be between 0.0 and 1.0.
  379. [[components.grid.renderer.custom]]
  380. === Custom Renderers
  381. Renderers are component extensions that require a client-side counterpart. See
  382. <<dummy/../../../framework/clientsidewidgets/clientsidewidgets-grid#clientsidewidgets.grid.renderers,"Renderers">>
  383. for information on implementing custom renderers.
  384. [[components.grid.headerfooter]]
  385. == Header and Footer
  386. A grid by default has a header, which displays column names, and can have a
  387. footer. Both can have multiple rows and neighbouring header row cells can be
  388. joined to feature column groups.
  389. [[components.grid.headerfooter.adding]]
  390. === Adding and Removing Header and Footer Rows
  391. A new header row is added with [methodname]#prependHeaderRow()#, which adds it
  392. at the top of the header, [methodname]#appendHeaderRow()#, which adds it at the
  393. bottom of the header, or with [methodname]#addHeaderRowAt()#, which inserts it
  394. at the specified 0-base index. All of the methods return a
  395. [classname]#HeaderRow# object, which you can use to work on the header further.
  396. [source, java]
  397. ----
  398. // Group headers by joining the cells
  399. HeaderRow groupingHeader = grid.prependHeaderRow();
  400. ...
  401. // Create a header row to hold column filters
  402. HeaderRow filterRow = grid.appendHeaderRow();
  403. ...
  404. ----
  405. Similarly, you can add footer rows with [methodname]#appendFooterRow()#,
  406. [methodname]#prependFooterRow()#, and [methodname]#addFooterRowAt()#.
  407. [[components.grid.headerfooter.joining]]
  408. === Joining Header and Footer Cells
  409. You can join two or more header or footer cells with the [methodname]#join()#
  410. method. For header cells, the intention is usually to create column grouping,
  411. while for footer cells, you typically calculate sums or averages.
  412. [source, java]
  413. ----
  414. // Group headers by joining the cells
  415. HeaderRow groupingHeader = grid.prependHeaderRow();
  416. HeaderCell namesCell = groupingHeader.join(
  417. groupingHeader.getCell("firstname"),
  418. groupingHeader.getCell("lastname")).setText("Person");
  419. HeaderCell yearsCell = groupingHeader.join(
  420. groupingHeader.getCell("born"),
  421. groupingHeader.getCell("died"),
  422. groupingHeader.getCell("lived")).setText("Dates of Life");
  423. ----
  424. [[components.grid.headerfooter.content]]
  425. === Text and HTML Content
  426. You can set the header caption with [methodname]#setText()#, in which case any
  427. HTML formatting characters are quoted to ensure security.
  428. [source, java]
  429. ----
  430. HeaderRow mainHeader = grid.getDefaultHeaderRow();
  431. mainHeader.getCell("firstname").setText("First Name");
  432. mainHeader.getCell("lastname").setText("Last Name");
  433. mainHeader.getCell("born").setText("Born In");
  434. mainHeader.getCell("died").setText("Died In");
  435. mainHeader.getCell("lived").setText("Lived For");
  436. ----
  437. To use raw HTML in the captions, you can use [methodname]#setHtml()#.
  438. [source, java]
  439. ----
  440. namesCell.setHtml("<b>Names</b>");
  441. yearsCell.setHtml("<b>Years</b>");
  442. ----
  443. [[components.grid.headerfooter.components]]
  444. === Components in Header or Footer
  445. You can set a component in a header or footer cell with
  446. [methodname]#setComponent()#. Often, this feature is used to allow filtering.
  447. ////
  448. // commented out until filtering is sorted for 8
  449. [[components.grid.filtering]]
  450. == Filtering
  451. The ability to include components in the grid header can be used to create
  452. filters for the grid data. Filtering is done in the container data source, so
  453. the container must be of type that implements
  454. [interfacename]#Container.Filterable#.
  455. [[figure.components.grid.filtering]]
  456. .Filtering Grid
  457. image::img/grid-filtering.png[width=50%, scaledwidth=80%]
  458. The filtering illustrated in <<figure.components.grid.filtering>> can be created
  459. as follows:
  460. [source, java]
  461. ----
  462. // Have a list of persons
  463. List<Person> people = getPeople();
  464. // Create a grid bound to it
  465. Grid<Person> grid = new Grid<>();
  466. grid.setItems(people);
  467. grid.setSelectionMode(SelectionMode.NONE);
  468. grid.setWidth("500px");
  469. grid.setHeight("300px");
  470. // Create a header row to hold column filters
  471. HeaderRow filterRow = grid.appendHeaderRow();
  472. // Set up a filter for all columns
  473. for (Column<?> col: grid.getColumns()) {
  474. HeaderCell cell = filterRow.getCell(col);
  475. // Have an input field to use for filter
  476. TextField filterField = new TextField();
  477. // Update filter When the filter input is changed
  478. filterField.addValueChangeListener(event -> {
  479. // Filter the list of items
  480. List<String> filteredList =
  481. // 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!
  482. Lists.newArrayList(personList.filter(persons,
  483. Predicates.containsPattern(event.getValue())));
  484. // Apply filtered data
  485. grid.setItems(filteredList);
  486. });
  487. cell.setComponent(filterField);
  488. }
  489. ----
  490. ////
  491. [[components.grid.sorting]]
  492. == Sorting
  493. A user can sort the data in a grid on a column by clicking the column header.
  494. Clicking another time on the current sort column reverses the sort direction.
  495. Clicking on other column headers while keeping the Shift key pressed adds a
  496. secondary or more sort criteria.
  497. [[figure.components.grid.sorting]]
  498. .Sorting Grid on Multiple Columns
  499. image::img/grid-sorting.png[width=50%, scaledwidth=75%]
  500. Defining sort criteria programmatically can be done with the various
  501. alternatives of the [methodname]#sort()# method. You can sort on a specific
  502. column with [methodname]#sort(Column column)#, which defaults to ascending
  503. sorting order, or [methodname]#sort(Column column, SortDirection
  504. direction)#, which allows specifying the sort direction.
  505. [source, java]
  506. ----
  507. grid.sort(nameColumn, SortDirection.DESCENDING);
  508. ----
  509. To sort on multiple columns, you need to use the fluid sort API with
  510. [methodname]#sort(Sort)#, which allows chaining sorting rules. Sorting rules are
  511. created with the static [methodname]#by()# method, which defines the primary
  512. sort column, and [methodname]#then()#, which can be used to specify any
  513. secondary sort columns. They default to ascending sort order, but the sort
  514. direction can be given with an optional parameter.
  515. [source, java]
  516. ----
  517. // Sort first by city and then by name
  518. grid.sort(Sort.by(cityColumn, SortDirection.ASCENDING)
  519. .then(nameColumn, SortDirection.DESCENDING));
  520. ----
  521. [[components.grid.editing]]
  522. == Editing Items Inside Grid
  523. Grid supports line-based editing, where double-clicking a row opens the row
  524. editor. In the editor, the input fields can be edited, as well as navigated with
  525. kbd:[Tab] and kbd:[Shift+Tab] keys. If validation fails, an error is displayed and the user
  526. can correct the inputs.
  527. The [classname]#Editor# is accessible via [methodname]#getEditor()#, and to enable editing, you need to call [methodname]#setEnabled(true)# on it.
  528. The editor is based on [classname]#Binder# which is used to bind the data to the editor.
  529. 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#.
  530. 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.
  531. 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.
  532. [source, java]
  533. ----
  534. List<Todo> items = Arrays.asList(new Todo("Done task", true),
  535. new Todo("Not done", false));
  536. Grid<Todo> grid = new Grid<>();
  537. TextField taskField = new TextField();
  538. CheckBox doneField = new CheckBox();
  539. Binder<Todo> binder = grid.getEditor().getBinder();
  540. Binding<Todo, Boolean> doneBinding = binder.bind(
  541. doneField, Todo::isDone, Todo::setDone);
  542. Column<Todo, String> column = grid.addColumn(
  543. todo -> String.valueOf(todo.isDone()));
  544. column.setWidth(75);
  545. column.setEditorBinding(doneBinding);
  546. grid.addColumn(Todo::getTask).setEditorComponent(
  547. taskField, Todo::setTask).setExpandRatio(1);
  548. grid.getEditor().setEnabled(true);
  549. ----
  550. [[components.grid.editing.buffered]]
  551. === Buffered / Unbuffered Mode
  552. Grid supports two editor modes - buffered and unbuffered. The default mode is
  553. buffered. The mode can be changed with [methodname]#setBuffered(false)#.
  554. In the buffered mode, editor has two buttons visible: a [guibutton]#Save# button that commits
  555. the modifications to the bean and closes the editor and a [guibutton]#Cancel# button
  556. discards the changes and exits the editor.
  557. Editor in buffered mode is illustrated in <<figure.components.grid.editing>>.
  558. [[figure.components.grid.editing]]
  559. .Editing a Grid Row
  560. image::img/grid-editor-basic.png[width=50%, scaledwidth=75%]
  561. In the unbuffered mode, the editor has no buttons and all changed data is committed directly
  562. to the data provider. If another row is clicked, the editor for the current row is closed and
  563. a row editor for the clicked row is opened.
  564. [[components.grid.editing.captions]]
  565. === Customizing Editor Buttons
  566. In the buffered mode, the editor has two buttons: [guibutton]#Save# and [guibutton]#Cancel#. You can
  567. set their captions with [methodname]#setEditorSaveCaption()# and
  568. [methodname]#setEditorCancelCaption()#, respectively.
  569. In the following example, we demonstrate one way to translate the captions:
  570. [source, java]
  571. ----
  572. // Localize the editor button captions
  573. grid.getEditor().setSaveCaption("Tallenna");
  574. grid.getEditor().setCancelCaption("Peruuta"));
  575. ----
  576. [[components.grid.editing.validation]]
  577. === Handling Validation Errors
  578. The input fields are validated when the value is updated. The default
  579. error handler displays error indicators in the invalid fields, as well as the
  580. first error in the editor.
  581. [[figure.components.grid.errors]]
  582. .Editing a Grid Row
  583. image::img/grid-editor-errors.png[width=50%, scaledwidth=75%]
  584. You can modify the error message by implementing a custom
  585. [interfacename]#EditorErrorGenerator# with for the [classname]#Editor#.
  586. ////
  587. // Not supported in 8
  588. [[components.grid.scrolling]]
  589. == Programmatic Scrolling
  590. You can scroll to first item with [methodname]#scrollToStart()#, to end with
  591. [methodname]#scrollToEnd()#, or to a specific row with [methodname]#scrollTo()#.
  592. ////
  593. [[components.grid.stylegeneration]]
  594. == Generating Row or Cell Styles
  595. You can style entire rows or individual cells with a
  596. [interfacename]#StyleGenerator#, typically used through Java lambdas.
  597. [[components.grid.stylegeneration.row]]
  598. === Generating Row Styles
  599. You set a [interfacename]#StyleGenerator# to a grid with
  600. [methodname]#setStyleGenerator()#. The [methodname]#getStyle()# method gets a
  601. date item, and should return a style name or [parameter]#null# if
  602. no style is generated.
  603. For example, to add a style names to rows having certain values in one
  604. property of an item, you can style them as follows:
  605. [source, java]
  606. ----
  607. grid.setStyleGenerator(person -> {
  608. // Style based on alive status
  609. person.isAlive() ? null : "dead";
  610. });
  611. ----
  612. You could then style the rows with CSS as follows:
  613. [source, css]
  614. ----
  615. .v-grid-row.dead {
  616. color: gray;
  617. }
  618. ----
  619. [[components.grid.stylegeneration.cell]]
  620. === Generating Cell Styles
  621. You set a [interfacename]#StyleGenerator# to a grid with
  622. [methodname]#setStyleGenerator()#. The [methodname]#getStyle()# method gets
  623. a [classname]#CellReference#, which contains various information about the cell
  624. and a reference to the grid, and should return a style name or [parameter]#null#
  625. if no style is generated.
  626. For example, to add a style name to a specific column, you can match on
  627. the column as follows:
  628. [source, java]
  629. ----
  630. // Static style based on column
  631. bornColumn.setStyleGenerator(person -> "rightalign");
  632. ----
  633. You could then style the cells with a CSS rule as follows:
  634. [source, css]
  635. ----
  636. .v-grid-cell.rightalign {
  637. text-align: right;
  638. }
  639. ----
  640. [[components.grid.css]]
  641. == Styling with CSS
  642. [source, css]
  643. ----
  644. .v-grid {
  645. .v-grid-scroller, .v-grid-scroller-horizontal { }
  646. .v-grid-tablewrapper {
  647. .v-grid-header {
  648. .v-grid-row {
  649. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  650. }
  651. }
  652. .v-grid-body {
  653. .v-grid-row,
  654. .v-grid-row-stripe,
  655. .v-grid-row-has-data {
  656. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  657. }
  658. }
  659. .v-grid-footer {
  660. .v-grid-row {
  661. .v-grid-cell, .frozen, .v-grid-cell-focused { }
  662. }
  663. }
  664. }
  665. .v-grid-header-deco { }
  666. .v-grid-footer-deco { }
  667. .v-grid-horizontal-scrollbar-deco { }
  668. .v-grid-editor {
  669. .v-grid-editor-cells { }
  670. .v-grid-editor-footer {
  671. .v-grid-editor-message { }
  672. .v-grid-editor-buttons {
  673. .v-grid-editor-save { }
  674. .v-grid-editor-cancel { }
  675. }
  676. }
  677. }
  678. }
  679. ----
  680. A [classname]#Grid# has an overall [literal]#++v-grid++# style. The actual grid
  681. has three parts: a header, a body, and a footer. The scrollbar is a custom
  682. element with [literal]#++v-grid-scroller++# style. In addition, there are some
  683. decoration elements.
  684. Grid cells, whether thay are in the header, body, or footer, have a basic
  685. [literal]#++v-grid-cell++# style. Cells in a frozen column additionally have a
  686. [literal]#++frozen++# style. Rows have [literal]#++v-grid-row++# style, and
  687. every other row has additionally a [literal]#++v-grid-row-stripe++# style.
  688. The focused row has additionally [literal]#++v-grid-row-focused++# style and
  689. focused cell [literal]#++v-grid-cell-focused++#. By default, cell focus is
  690. visible, with the border stylable with [parameter]#$v-grid-cell-focused-border#
  691. parameter in Sass. Row focus has no visible styling, but can be made visible
  692. with the [parameter]#$v-grid-row-focused-background-color# parameter or with a
  693. custom style rule.
  694. In editing mode, a [literal]#++v-grid-editor++# overlay is placed on the row
  695. under editing. In addition to the editor field cells, it has an error message
  696. element, as well as the buttons.
  697. ((()))