Grid with LitTemplate not updating checkbox consistently - checkbox

We are updating our Grid forms to use LitTemplates for rendering. However we have run into an issue with a checkbox state not being updated even though the underlying data for the state has been updated. The following code demonstrates the issue:
HorizontalLayout hlTest = new HorizontalLayout();
List<String> selected = new ArrayList<>();
Grid<String> testGrid =new Grid<>();
testGrid.setWidth("250px");
testGrid.setHeight("250px");
List<String> dataList = new ArrayList<>(List.of("AAAAA", "BBBBB", "CCCCC", "DDDDD", "EEEEE"));
ListDataProvider<String> dataProvider = new ListDataProvider<>(dataList);
testGrid.setItems(dataProvider);
String template = """
<vaadin-checkbox #click="${handleCheckClick}" ?checked="${item.rowSelected}"></vaadin-checkbox>
<div>${item.text}</div>
""";
LitRenderer<String> lit = LitRenderer.of(template);
lit.withProperty("rowSelected", item -> {
boolean rc = selected.contains(item);
System.out.println("Item selected: " + item + " => " + rc);
return rc;
});
lit.withProperty("text",item -> item);
lit.withFunction("handleCheckClick", (item) -> {
if(selected.contains(item))
selected.remove(item);
else
selected.add(item);
});
testGrid.addColumn(lit);
Button bSelect = new Button("Select");
bSelect.addClickListener(buttonClickEvent -> {
if(selected.size() > 0)
{
dataList.clear();
dataList.addAll(selected);
selected.clear();
dataProvider.refreshAll();
}
});
hlTest.add(testGrid, bSelect);
With the given grid, click a few checkboxes and click 'Select'. The list is reduced to the selected rows, but the checkboxes are still ticked even though 'selected' is empty. The logging within 'rowSelected' is correctly returning the state.
If I remove the column and re-add to grid, then all is displayed correctly. Also, if I select all items in the grid then the select also works correctly.
Currently using Java17 and Vaadin 22.0.6 (have also tried 23.0.0 beta3).
Thanks.

I think you need to call dataProvider refresh when you update
lit.withFunction("handleCheckClick", (item) -> {
if(selected.contains(item))
selected.remove(item);
else
selected.add(item);
testGrid().getDataProvider().refreshAll();
});

Related

ExtJS 7 - Column filter issue with locked column

I encountered this bug where the column filter is incorrect if the grid has a locked column
Here's the fiddle: sencha fillde
Steps to reproduce:
(Do not apply any filter)
Open the "Email" column menu
Open "Name" column menu (this is the locked column)
Open "Phone" column menu (notice that the filter menu is incorrect, it is showing the filter for "Email" column).
For grid that has no 'locked' columns the filter menu is working fine, thanks for anyone who can help!
Okay, this one was a bit tricky. It turns out that for a locked grid, the Ext.grid.filters.Filters:onMenuCreate gets hit twice... one for each side of the grid's menu that shows. The problem is that in the onMenuCreate, the framework doesn't account for the 2 menus. It only cares about the last menu that gets created and destroys the previous menu's listeners. In onMenuBeforeShow, the framework does account for each side of the grid, so I extended this idea into an override. I would encourage you to create a Sencha Support ticket for this, and if you don't have access, let me know, so I can submit one. Fiddle here.
Ext.override(Ext.grid.filters.Filters, {
onMenuCreate: function (headerCt, menu) {
var me = this;
// TODO: OLD BAD CODE... this would destroy the first menu's listeners
// if (me.headerMenuListeners) {
// Ext.destroy(me.headerMenuListeners);
// me.headerMenuListeners = null;
// }
// me.headerMenuListeners = menu.on({
// beforeshow: me.onMenuBeforeShow,
// destroyable: true,
// scope: me
// });
// Just like in the onMenuBeforeShow, we need to create a hash of our menus
// and their listeners... if we don't, we remove the 1st menu's listeners
// when the 2nd menu is created
if (!me.headerMenuListeners) {
me.headerMenuListeners = {};
}
var parentTableId = headerCt.ownerCt.id;
var menuListener = me.headerMenuListeners[parentTableId];
if (menuListener) {
Ext.destroy(menuListener);
me.headerMenuListeners[parentTableId] = null;
}
me.headerMenuListeners[parentTableId] = menu.on({
beforeshow: me.onMenuBeforeShow,
destroyable: true,
scope: me
});
},
destroy: function () {
var me = this,
filterMenuItem = me.filterMenuItem,
item;
// TODO: ADDING THIS AND REMOVING FROM THE Ext.destroy on the next line
var headerMenuListeners = this.headerMenuListeners;
Ext.destroy(me.headerCtListeners, me.gridListeners);
me.bindStore(null);
me.sep = Ext.destroy(me.sep);
for (item in filterMenuItem) {
filterMenuItem[item].destroy();
}
// TODO: ADDING THIS AND REMOVING FROM THE Ext.destroy on the next line
for (item in headerMenuListeners) {
headerMenuListeners[item].destroy();
}
this.callParent();
}
});

ExtJs 6 or 7 focus treelist item into view

I have this treelist with a toolbar that I use to create new elements (it's a document list) and I want to focus the newly created item. I can select it but I don't seem to find a way of focusing it:
const selected = documents.treeStore.getAt(documents.treeStore.findExact(
"documentId", current.id
));
if (selected) {
tree.cmp.setSelection(selected);
const node = tree.cmp.getSelection();// maybe redundant
// how do I focus this node into view?
}
If by focus you mean that the element should appear in the visibility range, you can use this method
ensureVisible
const selected = documents.treeStore.getAt(documents.treeStore.findExact(
"documentId", current.id
));
if (selected) {
var path = [];
do {
path.push(selected.getId());
}while (selected = selected.getRefOwner());
tree.cmp.expandPath('/' + path.reverse().join('/'), {focus:true});
}

How to get Selected Listbox Items using devexpress in winforms app?

I am trying to get selected item text. I used this below code
MessageBox.Show(listBoxColumnHeaders.SelectedItems);
Output
Devexpress.XtraEditors.BaseListboxControl+SelectedItemCollection
But my text is Country
Update
I add listbox items from another class. That class called FilterColumnHeader using below code
FilterControl fc = Application.OpenForms.OfType<FilterControl>().SingleOrDefault();
List<FilterColumnHeader> headers = new List<FilterColumnHeader>();
while (rd.Read())
{
headers.Add(new FilterColumnHeader { typeOfHeader = rd["type"].ToString(), columnHeadersName = rd["AsHeading"].ToString() });
}
fc.listBoxColumnHeaders.DisplayMember = "columnHeadersName";
fc.listBoxColumnHeaders.ValueMember = "typeOfHeader";
fc.listBoxColumnHeaders.DataSource = headers;
Now When I try to print using this below code,
MessageBox.Show(""+ listBoxColumnHeaders.SelectedItems[0].ToString());
It is showing in message box like below
`ProjectName.FilterColumnHeader`
The SelectedItems property returns a collection of selected objects. All you need to do is to cast the required object to your type:
var filterColumnHeader = (FilterColumnHeader)listBoxControl.SelectedItems[0];
I don't know if you found an answer but this works for me :
StringBuilder list = new StringBuilder();
foreach(var item in listBoxColumnHeaders.SelectedItems)
{
list.AppendLine(item as string);
}
MessageBox.Show(list.ToString());

How to add legends in Amserial charts

I am using Amcharts in my AngularJS Application to create a simple bar chart.The following is my code in the controller:
let empChart;
let empBarGraph;
let empLine;
const writeemp = data => {
const {
total,
employees,
} = data;
empChart.dataProvider = e;
empChart.write('emp');
empChart.validateData();
};
AmCharts.handleLoad();
var configChart = function () {
empChart = new AmCharts.AmSerialChart();
empChart.categoryField = "state";
empChart.labelRotation = 90;
var yAxis = new AmCharts.ValueAxis();
yAxis.position = "left";
empChart.addValueAxis(yAxis);
empBarGraph = new AmCharts.AmGraph();
empBarGraph.valueField = "count";
empBarGraph.type = "column";
empBarGraph.fillAlphas = 1;
empBarGraph.lineColor = "#f0ab00";
empBarGraph.valueAxis = yAxis;
empChart.addGraph(empBarGraph);
empChart.write('empChart');
$http.get(hostNameService.getHostName()+"/dashboard/employees/statecount")
.then(response => writeemp(response.data));
}
Code in html:
<div class='panel-body'>
<div id="empChart"></div>
</div>
This would return me the values of State on x-axis and count on y-axis. I wanted to filter the chart based on the value of state and was not sure how to create the legends for this chart. could anyone suggest me on how to use legends. I want to create legends for the state value that is being returned.
You can add a legend using the OO-based syntax by creating a legend object through new AmCharts.AmLegend() and adding it to the class by calling the chart's addLegend method:
var legend = new AmCharts.AmLegend();
empChart.addLegend(legend);
If you want the legend to show values upon hovering over a column, you need to add a ChartCursor to your chart:
var cursor = new AmCharts.ChartCursor();
empChart.addChartCursor(cursor);
You can change what the legend displays upon column rollover by setting the valueText property. It allows for the same [shortcodes] used in fields like balloonText and labelText, e.g. legend.valueText = "[[category]]: [[value]]". You can also use set its valueFunction if you need to customize the text it returns dynamically like in your previous questions. All of the properties available in the legend object can be found in the AmLegend API documentation.
Updated:
Legends work off of graph objects only, so there isn't an out of the box method that allows you to represent each column as a legend item that toggles the other columns' visibility unless you're willing to reorganize your dataset and use different graph objects for each state. A workaround for this is to use the the legend's custom data array and add some event handling so that clicking on the custom data items adds/removes a toggle by unsetting your count valueField in the dataProvider.
The following annotated code accomplishes what you're trying to do:
//create the legend but disable it until the dataProvider is populated,
//since you're retrieving your data using AJAX
var legend = new AmCharts.AmLegend();
legend.enabled = false;
chart.addLegend(legend);
chart.toggleLegend = false;
// Callback that handles clicks on the custom data entry markers and labels
var handleLegendClick = function(legendEvent) {
//Set a custom flag so that the dataUpdated event doesn't fire infinitely
legendEvent.chart.toggleLegend = true;
// The following toggles the markers on and off.
// The only way to "hide" a column is to unset the valueField at the data index,
// so a temporary "storedCount" property is added to the dataProvider that stores the
// original value so that the value can be restored when the legend marker is toggled
// back on
if (undefined !== legendEvent.dataItem.hidden && legendEvent.dataItem.hidden) {
legendEvent.dataItem.hidden = false;
legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count = legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].storedCount; //restore the value
} else {
// toggle the marker off
legendEvent.dataItem.hidden = true;
legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].storedCount = legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count; //store the value
legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count = undefined; //set to undefined to hide the column
}
legendEvent.chart.validateData(); //redraw the chart
}
chart.addListener('dataUpdated', function(e) {
var legendDataItems; //used to store the legend's custom data array.
if (e.chart.toggleLegend === true) {
//is the user toggling a legend marker? stop here as the dataProvider will get updated in handleLegendClick
e.chart.toggleLegend = false;
return;
}
// if we're at this point, the data provider was updated.
// reconstruct the data array.
// initialize by grabbing the state, setting a color and stoing the index
// for toggline the columns later
legendDataItems = e.chart.dataProvider.map(function(dataElement, idx) {
return {
'title': dataElement.state,
'color': graph.lineColor,
'stateIdx': idx //used in toggling
}
});
// if the legend is not enabled, then we're setting this up for the first time.
// turn it on and attach the event handlers
if (e.chart.legend.enabled === false) {
e.chart.legend.enabled = true;
e.chart.legend.switchable = true;
e.chart.legend.addListener('clickMarker', handleLegendClick);
e.chart.legend.addListener('clickLabel', handleLegendClick);
}
// update the legend custom data and redraw the chart
e.chart.legend.data = legendDataItems;
e.chart.validateNow();
});
Here's a fiddle that illustrates this: http://jsfiddle.net/g254sdq5/1/

How do I reset all filters in Extjs Grids?

How do I reset my ExtJS filters in my grids. More specifically, how do I get the header to honour the changes to the filtering.
ie. This works fine :
grid.store.clearFilter();
But the header rendering is all wrong. I need to get into all the menu objects and unselect the checkboxes.
I am getting pretty lost. I am pretty sure this gives me the filterItems :
var filterItems = grid.filters.filters.items;
And from each of these filter items, i can get to menu items like so :
var menuItems = filter.menu.items;
But that's as far as I can get. I am expecting some kind of checkbox object inside menu items, and then I can uncheck that checkbox, and hopefully the header rendering will then change.
UPDATE :
I now have this code. The grid store has its filter cleared. Next I get the filterItems from grid.filters.filters.items and iterate over them. Then I call a function on each of the menu items.
grid.store.clearFilter();
var filterItems = grid.filters.filters.items;
for (var i = 0; i<filterItems.length; i++){
var filter = filterItems[i];
filter.menu.items.each(function(checkbox) {
if (checkbox.setChecked)
checkbox.setChecked(false, true);
});
}
The checkboxes do get called, but still nothing is happening :(
Try this code:
grid.filters.clearFilters();
This should take care of both the grid and its underlying store.
When you do
grid.store.clearFilter();
it can only clear the filters on the store but the grid's view doesn't get updated with that call. Hence to handle it automatically for both the grid's view as well as the grid's store, just use
grid.filters.clearFilters();
Hope it helps!
Cheers!
Your update help me but you forget the case where you have input text instead of checkbox.
So this is my addition of your solution:
grid.filters.clearFilters();
var filterItems = grid.filters.filters.items;
for (var i = 0; i<filterItems.length; i++){
var filter = filterItems[i];
filter.menu.items.each(function(element) {
if (element.setChecked) {
element.setChecked(false, true);
}
if(typeof element.getValue !== "undefined" && element.getValue() !== "") {
element.setValue("");
}
});
}
When you use grid wiht gridfilters plugin
and inovoke
grid.filters.clearFilters();
it reset applyed filters, but it don't clean value in textfield inside menu.
For clean textfield text you can try this:
grid.filters.clearFilters();
const plugin = grid.getPlugin('gridfilters');
let activeFilter;
if('activeFilterMenuItem' in plugin) {
activeFilter = plugin.activeFilterMenuItem.activeFilter
}
if (activeFilter && activeFilter.type === "string") {
activeFilter.setValue("");
}

Resources