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

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