How to add tooltip for a item or cell of a vaadin table - tooltip

I noticed that vaadin 6.7.0 beta1 supports to add tooltip for row/cell of a table. However, I did not find any example how to add it.
Is there anybody who can provide some sample?

Use code as below:
table.setItemDescriptionGenerator(new ItemDescriptionGenerator() {
public String generateDescription(Component source, Object itemId, Object propertyId) {
if(propertyId == null){
return "Row description "+ itemId;
} else if(propertyId == COLUMN1_PROPERTY_ID) {
return "Cell description " + itemId +","+propertyId;
}
return null;
}}

You could accomplish this by setting a formfieldfactory. Here you could return a button that only loooks like text with styling CSS. This will let you set a caption on the button. This is obviously a ugly hack. More info about buttons and links in vaadin.
table.setTableFieldFactory(new TableFieldFactory() {
// container is the datasource
// item is the row
// property is the column
//
#Override
public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) {
})

You can't add tooltpis (setDescription) to a row/cell nativly - not yet!
It is already in there issue tracker but don't know when they will implement this feature

Related

Unkown Key in Vaadin 14 Grid during selection

I'm using a Grid in Vaadin 14. The grid is in multi-selection mode.
The selection handler takes a couple of seconds to complete and I'm calling setItems(...) at the end to update the items in the grid.
When the user selects another row while the previous selection handler is still running, I get an "Unknown key" error similar to the one described in https://github.com/vaadin/vaadin-grid-flow/issues/322, even though the new set of items still contains the selected item (another object instance but same according to equals()). This seems to be because the keys in the KeyMapper have already been changed due to setItems(), so the key coming from the client is not present anymore.
Is there a way to work around this, for example by disabling selection while the previous request is in progress?
UPDATE
To work around this Vaadin bug, I'm also calling setPageSize() with the exact number of items as argument. But it seems the same problem occurs even if I don't call setPageSize(), so it's probably due to setItems().
Do not change the grids items inside a SelectionListener.
You can still do all the things you wanted, but setting the items anew is not actually needed. In fact it will only create problems as you are experiencing now.
While working at this answer, I realized you will need to do your own Checkbox Column in order to be able to do actions for the one item that was just "selected", instead of removing all then add all selected ones (because much better performance). Here is how that could look.
// in my code samples, a `Foo` item can have many `Bar` items. The grid is of type Bar.
Grid.Column customSelectionColumn = grid.addComponentColumn(item -> {
Checkbox isSelected = new Checkbox();
isSelected.setValue(someParentFoo.getBars().contains(item));
isSelected.addValueChangeListener(event -> {
boolean newSelectedValue = event.getValue();
if(newSelectedValue){
someParentFoo.getBars().add(item)
} else {
someParentFoo.getBars().remove(item);
}
fooRepository.save(someParentFoo);
});
});
// make a Checkbox that selects all in the header
Checkbox toggleSelectAll = new Checkbox();
toggleSelectAll.addValueChangeListener(event -> {
if(event.getValue()){
someParentFoo.getBars().addAll(allGridItems);
} else {
someParentFoo.getBars().removeAll(allGridItems);
}
fooRepository.save(someParentFoo);
grid.getDataProvider().refreshAll(); // updates custom checkbox value of each item
});
gridHeaderRow.getCell(customSelectionColumn).setComponent(toggleSelectAll);
I solved this problem. Vaadin use data as key in HashMap. You need calc hashCode use immutable data fields. For example
public class TestData {
private int id;
private String name;
public TestData(int id) {
this.id = id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Vaadin Grid Row Index

In a vaadin table if we do
table.setRowHeaderMode(RowHeaderMode.INDEX);
we get a column with the row index.
Is it possible to to the same with a vaadin grid?
So far I haven't seen such an option, but you should be able to fake it with a generated column. Please see below a naive implementation which should get you started (improvements and suggestions are more than welcome):
// our grid with a bean item container
Grid grid = new Grid();
BeanItemContainer<Person> container = new BeanItemContainer<>(Person.class);
// wrap the bean item container so we can generated a fake header column
GeneratedPropertyContainer wrappingContainer = new GeneratedPropertyContainer(container);
wrappingContainer.addGeneratedProperty("rowHeader", new PropertyValueGenerator<Long>() {
private long index = 0;
#Override
public Long getValue(Item item, Object itemId, Object propertyId) {
return index++;
}
#Override
public Class<Long> getType() {
return Long.class;
}
});
// assign the data source to the grid and set desired column order
grid.setContainerDataSource(wrappingContainer);
grid.setColumnOrder("rowHeader", "name", "surname");
// tweak it a bit - definitely needs more tweaking
grid.getColumn("rowHeader").setHeaderCaption("").setHidable(false).setEditable(false).setResizable(false).setWidth(30);
// freeze the fake header column to prevent it from scrolling horizontally
grid.setFrozenColumnCount(1);
// add dummy data
layout.addComponent(grid);
for (int i = 0; i < 20 ; i++) {
container.addBean(new Person("person " + i, "surname " + i));
}
This will generate something similar to the image below:
There is a Grid Renderer that can be used to do this now. It is in the grid renderers add-on https://vaadin.com/directory/component/grid-renderers-collection-for-vaadin7. It is compatible with Vaadin 8 as well.
Here is how it could be used (there are a few different options for how to render the index).
grid.addColumn(value -> "", new RowIndexRenderer()).setCaption("Row index");
Worth to mention that I use the following with Vaadin 18 flow and works perfectly.
grid.addColumn(TemplateRenderer.of("[[index]]")).setHeader("#");
Ok, it took me more than a while to figure this out. I don't know why you need this, but if your purpose is to find which grid row was clicked, then you can get the index from the datasource of your control via the itemClick event of your listener.
In my case, my datasource is an SQLContainer, and I already had it available (see ds var) so I did it this way:
grid.addListener(new ItemClickEvent.ItemClickListener() {
#Override
public void itemClick(ItemClickEvent event) {
Object itemId = event.getItemId();
int indexOfRow = ds.indexOfId(itemId);
}
});
You usually add a datasource to your control when you initialize it, via constructor or by setting the property. If you got you Grid from somewhere with an already-attached datasource, you can always get it with something like this:
SQLContainer ds = (SQLContainer)gred.getContainerDataSource();
I use this trick:
int i = 0;
grid.addComponentColumn(object -> {
i++;
return new Label("" + i);
}).setCaption("");

How does the Vaadin table work with Navigator?

I'm writing a view which navigates to a table entry's page displayed on the left side when a table entry (on the right) is chosen. This is similar to the addressbook tutorial on Vaadin's site, only I make use of the Navigator and views.
While I got the navigation to work (clicking on entry with id #12 navigates to localhost:8080/test/12) and a test label in the view's enter() gets changed to match the id, testTable.getItem(event.getParameters()) returns null for some reason so I can't access the entry.
The ValueChangeListener and enter() for the view are shown below.
class ValueChangeListener implements Property.ValueChangeListener {
Object testId;
#Override
public void valueChange(ValueChangeEvent event) {
// Navigate to a chosen table entry
this.testId = event.getProperty().getValue();
navigator.navigateTo("test/" + testId);
}
}
...
public void enter(ViewChangeEvent event) {
Object tmp = event.getParameters();
testName.setValue((String) tmp); // is set to the id
System.out.println(testTable.getItem(tmp) == null); // DEBUG: always returns true
}
I think you should change this:
System.out.println(testTable.getItem(tmp) == null);
to this:
String str = (String) tmp;
if (str != null && !str.isEmpty()) {
System.out.println(testTable.getItem(Integer.parseInt(str)) == null);
}
I think there's something wrong in how you manage you Navigator.
Firstly when you change view with Navigator you who should add a proper "URL fragment" with "#".
For example the Vaadin sampler uses:
http://demo.vaadin.com/sampler/#foundation
If in your URL there's no "#" ViewChangeEvent.getParameters() gives you null or isEmpty().

Validation icon not shown in Table fields

When I enter edit mode of my Table, I want the data validation exclamation mark icon (!) to be shown as soon as the user goes out of bounds of any of the validation constraints.
First, a couple of notes:
I'm using Vaadin 7, so the Bean Validation addon sadly won't work.
The data validation works as intended.
Now, I have a perfectly working table for which I am using a BeanItemContainer to keep my Person beans inside.
The code for the table and the TableFieldFactory looks something like this:
table.setContainerDataSource(buildContainer());
table.setTableFieldFactory(new TableFieldFactory() {
#Override
public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) {
TextField field = (TextField) DefaultFieldFactory.get().createField(container, itemId, propertyId,
uiContext);
field.setImmediate(true);
if (propertyId.equals("firstName")) {
field.addValidator(new BeanValidator(Person.class, "firstName"));
}
return field;
}
});
The Person bean looks as follows:
public class Person {
#Size(min = 5, max = 50)
private String firstName;
... setters + getters...
}
The problem is that when I type something in the firstName field and then press enter or blur/unfocus that field, no indication whatsoever of error is shown. I have to mouseover the field to see that something is wrong.
My question is two folded...
How do I get the exclamation mark icon to appear when the field is
invalid? (This works for a normal TextField that is not in a Table)
Is there a way to get an immediate response from the invalid field
(show the icon) (i.e. immediately after you type under 5 chars,
without having to press enter or blur/unfocus the field in
question).
Would be great if I could have both questions answered! =)
Thanks in advance!
The Caption, Required Indicator (the red asterisk) and - most importantly here - Error Indicator (exclamation mark) are actually provided by the layouts containing the component, not the component themselves. When editable components are displayed in a table, they are displayed without a layout - that's why no error indicator is displayed.
If I were trying to square this circle, I would look at creating a CustomField as a wrapper for the editable field - and within that CustomField display an error indicator when the wrapped/delegate field becomes invalid. I've not tried this - I've not used editable fields in a table at all - but should be fairly easy to do.
Add a TextChangeListener to the field in FieldFactory, and call field.validate() in the listener. Note, though, that field.getValue() value is not normally changed until blur/unfocus, ergo the validator will be validating the old value - unless you do field.setValue(event.getText()) in the listener. See this post on the Vaadin forum for more details.
This is the sort of thing I meant for a validating wrapper - not tried using it. You'll see initComponent simply returns the field inside a FormLayout, which should give you the icon(s) you're seeking. (You may need to delegate more methods from ValidatingWrapper to delegate than I have- but quick look suggests this may be enough.)
You'd then wrap the field in your tableFieldFactory (second code block)
public class ValidatingWrapper<T> extends CustomField<T> {
private static final long serialVersionUID = 9208404294767862319L;
protected Field<T> delegate;
public ValidatingWrapper(final Field<T> delegate) {
this.delegate = delegate;
if (delegate instanceof TextField) {
final TextField textField = (TextField) delegate;
textField.setTextChangeEventMode(AbstractTextField.TextChangeEventMode.TIMEOUT);
textField.setTextChangeTimeout(200);
textField.addTextChangeListener(new FieldEvents.TextChangeListener() {
#Override
public void textChange(FieldEvents.TextChangeEvent event) {
textField.setValue(event.getText());
textField.validate();
}
});
}
}
#Override
public Class<? extends T> getType() {
return delegate.getType();
}
#Override
protected Component initContent() {
return new FormLayout(delegate);
}
#Override
public Property getPropertyDataSource() {
return delegate.getPropertyDataSource();
}
#Override
public void setPropertyDataSource(Property newDataSource) {
delegate.setPropertyDataSource(newDataSource);
}
}
table.setContainerDataSource(buildContainer());
table.setTableFieldFactory(new TableFieldFactory() {
#Override
public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) {
TextField field = (TextField) DefaultFieldFactory.get().createField(container, itemId, propertyId,
uiContext);
field.setImmediate(true);
if (propertyId.equals("firstName")) {
field.addValidator(new BeanValidator(Person.class, "firstName"));
}
return ValidatingWrapper(field);
}
});

smartgwt listgrid set cursor to hand over an icon field

I've been working on this problem for quite a while but have not been able to solve it.
I have a listgrid with a field type icon. I would like to change the cursor to "hand" over the icon.
I've been searching the web and saw that a couple of solutions existed.
One of them is using addCellOverHandler for the list grid. But I don't understand how you can change the cursor for the specified field of the listgrid.
this.addCellOverHandler(new CellOverHandler() {
#Override
public void onCellOver(CellOverEvent event) {
// not able to get the field and setCursor()
}
});
My field in the listgrid is defined as:
ListGridField iconField = new ListGridField("icon");
iconField.setAlign(Alignment.CENTER);
iconField.setType(ListGridFieldType.ICON);
iconField.setIcon("icons/icon.gif");
Like someone pointed out on the forum, a setCursor() method exist for the listgrid, but not for the field only...
If anybody has a clue...
Thanks
After some more (a lot more...) googling, I found this:
http://forums.smartclient.com/showthread.php?t=15748
The thing is to Override the getCellStyle method in the listgrid.
Here is the code I use:
#Override
protected String getCellStyle(ListGridRecord record, int rowNum, int colNum) {
if (colNum==6){
return "EC_pointer";
}
return super.getCellStyle(record, rowNum, colNum);
}
and in my CSS file:
.EC_pointer {
cursor: pointer;
}
The major fallout is that you have to know in advance the column number of the field.
Further to my comment and adding information from here I tested the following code which works with SmartGwt2.4 under Firefox 5.0.
demandesGrid.setCanHover(true);
demandesGrid.setShowHover(false);
demandesGrid.addCellHoverHandler(new CellHoverHandler() {
#Override
public void onCellHover(CellHoverEvent event) {
if (event.getColNum() == demandesGrid.getFieldNum("icon")) {
// SC.say(demandesGrid.getChildren()[3].toString());
demandesGrid.getChildren()[3].setCursor(Cursor.POINTER);
} else {
demandesGrid.getChildren()[3].setCursor(Cursor.DEFAULT);
}
}
});
I don't know if the index of the ListGridBody is constant; I found it with the SC.say line.
How about
grid.addCellOverHandler(new CellOverHandler() {
#Override
public void onCellOver(CellOverEvent event) {
//cellOver event to get field and refresh the cell
//grid.refreshCell(i, j);
}
});
The best approach is fully demonstrated here (take a look at how "comments/stats" field is being initialized).
In short, u have to extend ListGrid and override createRecordComponent method. In this method you can make any custom component you like and it will be show in grid cell.
Also ListGrid should be initialized with:
listGrid.setShowRecordComponents(true);
listGrid.setShowRecordComponentsByCell(true);

Resources