How to get the row index of a Grid Element (Vaadin Flow) - vaadin-flow

I am using Vaadin 14 (currently rc7).
Getting the row index of a Grid with a ListDataProvider is simple. I use the code below.
final Collection<T> c = ((ListDataProvider)grid.getDataProvider()).getItems();
final List<T> list;
if (c instanceof List) {
list = (List)c;
} else {
list = new ArrayList(c);
}
return list.indexOf(item);
However, how to get this in the generic use case, not assuming a ListDataProvider?
Use Case
Make a specific row visible in the Grid based on some app logic, so "scroll to a row".

Related

BeanItemContainer unique property values

I am using BeanItemContainer for my Grid. I want to get a unique list of one of the properties. For instance, let's say my beans are as follows:
class Fun {
String game;
String rules;
String winner;
}
This would display as 3 columns in my Grid. I want to get a list of all the unique values for the game property. How would I do this? I have the same property id in multiple different bean classes, so it would be nice to get the values directly from the BeanItemContainer. I am trying to avoid building this unique list before loading the data into the Grid, since doing it that way would require me to handle it on a case by case basis.
My ultimate goal is to create a dropdown in a filter based on those unique values.
There isn't any helper for directly doing what you ask for. Instead, you'd have to do it "manually" by iterating through all items and collecting the property values to a Set which would then at the end contain all unique values.
Alternatively, if the data originates from a database, then you could maybe retrieve the unique values from there by using e.g. the DISTINCT keyword in SQL.
In case anyone is curious, this is how I applied Leif's suggestion. When they enter the dropdown, I cycle through all the item ids for the property id of the column I care about, and then fill values based on that property id. Since the same Grid can be loaded with new data, I also have to "clear" this list of item ids.
filterField.addFocusListener(focus->{
if(!(filterField.getItemIds() instanceof Collection) ||
filterField.getItemIds().isEmpty())
{
BeanItemContainer<T> container = getGridContainer();
if( container instanceof BeanItemContainer && getFilterPropertyId() instanceof Object )
{
List<T> itemIds = container.getItemIds();
Set<String> distinctValues = new HashSet<String>();
for(T itemId : itemIds)
{
Property<?> prop = container.getContainerProperty(itemId, getFilterPropertyId());
String value = null;
if( prop.getValue() instanceof String )
{
value = (String) prop.getValue();
}
if(value instanceof String && !value.trim().isEmpty())
distinctValues.add(value);
}
filterField.addItems(distinctValues);
}
}
});
Minor point: the filterField variable is using the ComboBoxMultiselect add-on for Vaadin 7. Hopefully, when I finally have time to convert to Vaadin 14+, I can do something similar there.

Vaadin Chart: Second and Subsequent Item Does Not Show on Each X-Tick in Column Stack Chart

Base on the resultset below, I have created a column stack chart. They have been converted to an 4-attribrute object list (called as SKUQtyMetric - all are strings except for Quantity as Integer)
When converting this to a stack chart, I could not get the second item to appear next to the first item in each of the x-ticks (X represents hour). If I am not mistaken, there should only be four DataSeries objects, each representing an outlet and then do an inner loop. Just as a side note, each outlet is designated a color even if there's more than one item (I am keeping a limit of three items to be selected for searching in database), hence there's the outletFromH code below.
The current rendering of the code (using Vaadin Charts 4) is as below:
Map<String, Set<String>> myMaps = new HashMap<String, Set<String>>();
for (SkuQtyMetric item : objList) {
if (!myMaps.containsKey(item.getOutletName())) {
myMaps.put(item.getOutletName(), new HashSet<String>());
}
myMaps.get(item.getOutletName()).add(item.getItemName());
}
String asgnColor = "#ffcccc";
for(Map.Entry<String, Set<String>> map: myMaps.entrySet()) {
DataSeries dataSeries = new DataSeries(map.getKey()+"");
PlotOptionsColumn plotOptions = new PlotOptionsColumn();
plotOptions.setStacking(Stacking.NORMAL);
DataLabels labels = new DataLabels(true);
Style style = new Style();
style.setFontSize("9px");
style.setTextShadow("0 0 3px black");
labels.setStyle(style);
labels.setColor(new SolidColor("white"));
plotOptions.setDataLabels(labels);
ls.add(dataSeries);
for(String itemName: map.getValue()) {
System.out.println("Inside " + map.getKey() + ", value is: " + itemName);
dataSeries.setId(itemName);
for(SkuQtyMetric metric : objList) {
for (Map.Entry<String, String> outletfromH : Constant.SYCARDA_COLOR.entrySet()) {
if (outletfromH.getKey().equalsIgnoreCase(map.getKey())) {
asgnColor = outletfromH.getValue();
}
}
System.out.println("DataSeries Id: " + dataSeries.getId() + " , Item metric name is: "+metric.getItemName());
if(dataSeries.getName().equalsIgnoreCase(metric.getOutletName())) {
if(dataSeries.getId().equalsIgnoreCase(metric.getItemName())) {
DataSeriesItem dataSeriesItem = new DataSeriesItem(xFor(metric.getHourNumber()), metric.getQuantityAmt());
dataSeriesItem.setId(metric.getItemName()+"_setSeriesId");
dataSeriesItem.setColor(new SolidColor(asgnColor));
dataSeries.setStack(metric.getItemName());
plotOptions.setColor(new SolidColor(asgnColor));
dataSeries.setPlotOptions(plotOptions);
dataSeries.add(dataSeriesItem);
}
}
}
}
}
for (int j = 0; j < ls.size(); j++) {
listSeries.add(ls.get(j));
}
chart.getConfiguration().getSubTitle().setText(subpageName);
chart.getConfiguration().setSeries(listSeries);
When rendered, I could only get this result:
That's the current chart but second item (coconut water) is missing, shown with red scribbling. What I am not sure is whether my Map class OR my list objects controlled isn't correct OR it might be that there should be eight not four DataSeries (each being a outlet and a product). If not, is there a much more efficient way to handle the code to render the chart than what I am doing right now?
It should be possible to have multiple DataSeriesItem in the same series that go in the same stack. Four series should be enough, no need to have 8.
You can do it by setting the name of the DataSeriesItem and set the XAxis type to category so that the categories are computed from the point names.
Or by setting numeric X values to the DataSeriesItem and setting the categories to the XAxis as a String[].
Having separate series makes some things easier, like tooltips, and showing/hiding data from the legend. But in theory everything can be in a single series.
In some cases you might need to be sure that data is sorted by X value, or by name if you use the name as categories otherwise some points might not show correctly, you can check if that's your case by checking the browser console for error or warnings about that.

How do you add an initial selection for Angular Material Table SelectionModel?

The Angular Material documentation gives a nice example for how to add selection to a table (Table Selection docs). They even provide a Stackblitz to try it out.
I found in the code for the SelectionModel constructor that the first argument is whether there can be multiple selections made (true) or not (false). The second argument is an array of initially selected values.
In the demo, they don't have any initially selected values, so the second argument in their constructor (line 36) is an empty array ([]).
I want to change it so that there is an initially selected value, so I changed line 36 to:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
This changes the checkbox in the header to an indeterminate state (as expected), but does not cause the row in the table to be selected. Am I setting the initial value incorrectly, or what am I missing here? How can I set an initially selected value?
Tricky one. You need to initialize the selection by extracting that particular PeriodicElement object from your dataSource input, and passing it to the constructor.
In this particular case, you could code
selection = new SelectionModel<PeriodicElement>(true, [this.dataSource.data[1]);
It's because of the way SelectionModel checks for active selections.
In your table markup you have
<mat-checkbox ... [checked]="selection.isSelected(row)"></mat-checkbox>
You expect this binding to mark the corresponding row as checked. But the method isSelected(row) won't recognize the object passed in here as being selected, because this is not the object your selection received in its constructor.
"row" points to an object from the actual MatTableDataSource input:
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
But the selection initialization:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
happens with a new object you create on the fly. Your selection remembers THIS object as a selected one.
When angular evaluates the bindings in the markup, SelectionModel internally checks for object identity. It's going to look for the object that "row" points to in the internal set of selected objects.
Compare to lines 99-101 and 16 from the SelectionModel source code:
isSelected(value: T): boolean {
return this._selection.has(value);
}
and
private _selection = new Set<T>();
I was facing the same issue, I used dataSource to set the initial value manually in ngOnInit()
ngOnInit() {
this.dataSource.data.forEach(row => {
if (row.symbol == "H") this.selection.select(row);
});
}
If you do the following, it works too
selection = new SelectionModel<PeriodicElement>(true, [ELEMENT_DATA[1]])
To select all you can do
selection = new SelectionModel<PeriodicElement>(true, [...ELEMENT_DATA])
I hope the answer is helpful
Or more dynamically if you have a set of values and you want to filter them before:
selection = new SelectionModel<PeriodicElement>(true, [
...this.dataSource.data.filter(row => row.weight >= 4.0026)
]);
This gets more tricky if you have data loading asynchronously from an api. Here is how I did it:
Firstly I have implemented the DataSource from "#angular/cdk/table". I also have an RxJS Subject that fires whenever data is loaded (first time or when user changes page in the pagination section)
export abstract class BaseTableDataSource<T> implements DataSource<T>{
private dataSubject = new BehaviorSubject<T[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
private totalRecordsSubject = new BehaviorSubject<number>(null);
public loading$ = this.loadingSubject.asObservable();
public dataLoaded$ = this.dataSubject.asObservable();
public totalRecords$ = this.totalRecordsSubject.asObservable().pipe(filter(v => v != null));
constructor(){}
connect(collectionViewer: CollectionViewer): Observable<T[]>{
return this.dataSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.dataSubject.complete();
this.loadingSubject.complete();
this.totalRecordsSubject.complete();
}
abstract fetchData(pageIndex, pageSize, ...params:any[]) : Observable<TableData<T>>;
abstract columnMetadata(): {[colName: string]: ColMetadataDescriptor };
loadData(pageIndex, pageSize, params?:any[]): void{
this.loadingSubject.next(true);
this.fetchData(pageIndex, pageSize, params).pipe(
finalize(() => this.loadingSubject.next(false))
)
.subscribe(data => {
this.totalRecordsSubject.next(data.totalNumberOfRecords);
this.dataSubject.next(data.records)
});
}
}
Now when I want to pre-select a row, I can write a function like this in my component which hosts a table that uses an implementation of the above mentioned data source
selectRow(rowSelectionFn: (key: string) => boolean){
this.dataSource.dataLoaded$.pipe(takeUntil(this.destroyed$))
.subscribe(data => {
const foundRecord = data.filter(rec => rowSelectionFn(rec));
if(foundRecord && foundRecord.length >= 0){
this.selection.toggle(foundRecord[0]);
}
});
}

Vaadin7 table sort label column numerically

I have vaadin table with multiple columns. One of the column is of label class
container.addContainerProperty(ID_COLUMN, Label.class, "");
and I fill it up like
referenceItem.getItemProperty(ID_COLUMN).setValue(new Label(new Integer(reference.getId()).toString()));
When I sort the table by clicking on this table, it sorts the data like
1
10
100
2
200
7
So, I tried to change the class to Integer, then it works fine, but I get the numbers with comma like
1
2
...
..
7,456
8,455
How can I have the data sorted numerically and no commas.
I was able to figure out. I used Integer as class for my column and used following
referenceTable = new Table()
{
#Override
protected String formatPropertyValue(final Object a_row_id, final Object a_col_id, final Property<?> a_property)
{
if (a_property.getType() == Integer.class && null != a_property.getValue())
{
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(getLocale());
df.applyLocalizedPattern("#0");
return df.format(a_property.getValue());
}
return super.formatPropertyValue(a_row_id, a_col_id, a_property);
}
};
It has been a while since i have been having fun with Vaadin Table.
There are property formatters, generators etc... stuff but in this case it might be easiest just to:
container.addContainerProperty(ID_COLUMN, String.class, "");
referenceItem.getItemProperty(ID_COLUMN).setValue(""+reference.‌​getId());

How to index sub-content in Sitecore with Lucene?

I'm using Sitecore 7.2 with MVC and a component approach to page building. This means that pages are largely empty and the content comes from the various renderings placed on the page. However, I would like the search results to return the main pages, not the individual content pieces.
Here is the basic code I have so far:
public IEnumerable<Item> GetItemsByKeywords(string[] keywords)
{
var index = ContentSearchManager.GetIndex("sitecore_master_index");
var allowedTemplates = new List<ID>();
IEnumerable<Item> items;
// Only Page templates should be returned
allowedTemplates.Add(new Sitecore.Data.ID("{842FAE42-802A-41F5-96DA-82FD038A9EB0}"));
using (var context = index.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
{
var keywordsPredicate = PredicateBuilder.True<SearchResultItem>();
var templatePredicate = PredicateBuilder.True<SearchResultItem>();
SearchResults<SearchResultItem> results;
// Only return results from allowed templates
templatePredicate = allowedTemplates.Aggregate(templatePredicate, (current, t) => current.Or(p => p.TemplateId == t));
// Add keywords to predicate
foreach (string keyword in keywords)
{
keywordsPredicate = keywordsPredicate.And(p => p.Content.Contains(keyword));
}
results = context.GetQueryable<SearchResultItem>().Where(keywordsPredicate).Filter(templatePredicate).GetResults();
items = results.Hits.Select(hit => hit.Document.GetItem());
}
return items;
}
You could create a computed field in the index which looks at the renderings on the page and resolves each rendering's data source item. Once you have each of those items you can index their fields and concatenate all of this data together.
One option is to do this with the native "content" computed field which is natively what full text search uses.
An alternative solution is to make an HttpRequest back to your published site and essentially scrape the HTML. This ensures that all renderings are included in the index.
You probably will not want to index common parts, like the Menu and Footer, so make use of HTMLAgilityPack or FizzlerEx to only return the contents of a particular parent container. You could get more clever to remove inner containers is you needed to. Just remember to strip out the html tags as well :)
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
//get the page
var web = new HtmlWeb();
var document = web.Load("http://localsite/url-to-page");
var page = document.DocumentNode;
var content = page.QuerySelector("div.main-content");

Resources