How to reload data rows in GXT grid? - gwt

Assuming that data retrieves from DataStore using RPCproxy, populate to grid using ListStore upon opening the page.
Then, there's a form to add an entity and after modification it will reflect the new list in GXT grid with the new added row.
How can reload the grid? I tried .reconfigure() method in Grid but didn't work.

grid.getStore().getLoader().load();
update:
First of all you must extract Grid before your Proxy, and the second thing is to change your RPC callback:
public class PagingBeanModelGridExample extends LayoutContainer {
//put grid Class outside a method or declare it as a final on the begin of a method
Grid grid = null;
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
RpcProxy> proxy = new RpcProxy>() {
#Override
public void load(Object loadConfig, final AsyncCallback> callback) {
//modification here - look that callback is overriden not passed through!!
service.getBeanPosts((PagingLoadConfig) loadConfig, new AsyncCallback>() {
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
public void onSuccess(PagingLoadResult result) {
callback.onSuccess(result);
//here you are reloading store
grid.getStore().getLoader().load();
}
});
}
};
// loader
final BasePagingLoader> loader = new BasePagingLoader>(proxy, new BeanModelReader());
ListStore store = new ListStore(loader);
List columns = new ArrayList();
//...
ColumnModel cm = new ColumnModel(columns);
grid = new Grid(store, cm);
add(grid);
}
}

To display the new data to grid do you really need to reload the grid?
You can create a new model object with the new data and add this to the ListStore.
Suppose you have a CommentModel which extends the BaseModel and a ListStore of Comment model commentStore.
final ListStore<Commentmodel> commentStore = new ListStore<Commentmodel>();
//now call a rpc to load all available comments and add this to the commentStore.
commentService.getAllComment(new AsyncCallback<List<Commentmodel>>() {
#Override
public void onFailure(Throwable caught) {
lbError.setText("data loading failure");
}
#Override
public void onSuccess(List<Commentmodel> result) {
commentStore.add(result);
}
});
commentService is an AsyncService.
Now if a user post a comment, just create a new CommentModel object with the new data
CommentModel newData = new CommentModel('user name', 'message','date');
And add this to the commentStore.
commentStore.add(newData);
Hope this will serve you purpose.
But if you really need to reload the whole set of data, call the service again. In the onSuccess method first clear the commentStore then add result. Remember this is more more time consuming that the 1st approach.

Related

Dynamic DataGrid in GWT

I am trying to construct a DataGrid in GWT that will show an arbitrary dataset taken from an rpc method.
I have done some progress as I get the fields from a method and the data from another.
I have managed to construct the Datagrid and add the columns from the rpc.getFields() method and fill the table using an AsyncDataProvider.
The problem is that when I refresh the browser, it duplicates all the columns at the Datagrid. I cannot figure out what to do. I tried to remove first all the columns but no luck.
I attach the code if anyone have an idea.
public class MyCallBack implements AsyncCallback<List<Field>> {
DataGrid<Record> dg;
public MyCallBack(DataGrid<Record> dgrid) {
this.dg=dgrid;
}
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
public void onSuccess(List<Field> result) {
for (int i=0;i<=result.size();i++) {
IndexedColumn ic = new IndexedColumn(i);
dg.addColumn(ic, result.get(i).getLabel());
}
}
public AsyncCallback<List<Field>> getCb() {
return this;
}
public void onModuleLoad() {
final DataGrid<Record> dg = new DataGrid<Record>();
MyCallBack mcb = new MyCallBack(dg);
DataProvider dp = new DataProvider();
DBConnectionAsync rpcService = (DBConnectionAsync) GWT.create(DBConnection.class);
ServiceDefTarget target = (ServiceDefTarget) rpcService;
String moduleRelativeURL = GWT.getModuleBaseURL() + "MySQLConnection";
target.setServiceEntryPoint(moduleRelativeURL);
rpcService.getFields(mcb.getCb());
dp.addDataDisplay(dg);
dg.setVisibleRange(0, 200);
SplitLayoutPanel slp = new SplitLayoutPanel();
slp.setHeight("700px");
slp.setWidth("1500px");
slp.addWest(dg, 770);
RootPanel.get().add(slp);
}
When you refresh a browser, all UI is lost. There is no difference between (a) show the UI for the first time or (b) show the UI after browser refresh.
Your comment "Only if I restart tomcat it works" suggests that the problem is on the server side. Most likely, you return twice the number of data points on a second call.
Try clearing the table before filling it like this:
public void onSuccess(List<Field> result) {
clearTable();
for (int i=0;i<=result.size();i++) {
IndexedColumn ic = new IndexedColumn(i);
dg.addColumn(ic, result.get(i).getLabel());
}
}
private void clearTable(){
while (dg.getColumnCount() > 0) {
db.removeColumn(0);
}
}

Delete rows from Nattable

I want to implement a row deletion logic in a Nebula Nattable.
This is what I plan to do:
Add context menu to the Nattable which is described in http://blog.vogella.com/2015/02/03/nattable-context-menus-with-eclipse-menus/
Add an SWT Action to the menu which will implement the delete
my question is, which is the best way to accomplish this:
Should I delete the corresponding value from my data model and the table view is refreshed when I execute this.natview.refresh();?
OR
Should I get the rows from SelectionLayer and delete them (if so how do I do ?)?
OR
is there any default support for this function through IConfiguration?
In NatTable you would typically do the following:
Create a command for deleting a row
public class DeleteRowCommand extends AbstractRowCommand {
public DeleteRowCommand(ILayer layer, int rowPosition) {
super(layer, rowPosition);
}
protected DeleteRowCommand(DeleteRowCommand command) {
super(command);
}
#Override
public ILayerCommand cloneCommand() {
return new DeleteRowCommand(this);
}
}
Create a command handler for that command
public class DeleteRowCommandHandler<T> implements ILayerCommandHandler<DeleteRowCommand> {
private List<T> bodyData;
public DeleteRowCommandHandler(List<T> bodyData) {
this.bodyData = bodyData;
}
#Override
public Class<DeleteRowCommand> getCommandClass() {
return DeleteRowCommand.class;
}
#Override
public boolean doCommand(ILayer targetLayer, DeleteRowCommand command) {
//convert the transported position to the target layer
if (command.convertToTargetLayer(targetLayer)) {
//remove the element
this.bodyData.remove(command.getRowPosition());
//fire the event to refresh
targetLayer.fireLayerEvent(new RowDeleteEvent(targetLayer, command.getRowPosition()));
return true;
}
return false;
}
}
Register the command handler to the body DataLayer
bodyDataLayer.registerCommandHandler(
new DeleteRowCommandHandler<your type>(bodyDataProvider.getList()));
Add a menu item to your menu configuration that fires the command
new PopupMenuBuilder(natTable)
.withMenuItemProvider(new IMenuItemProvider() {
#Override
public void addMenuItem(NatTable natTable, Menu popupMenu) {
MenuItem deleteRow = new MenuItem(popupMenu, SWT.PUSH);
deleteRow.setText("Delete");
deleteRow.setEnabled(true);
deleteRow.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent event) {
int rowPosition = MenuItemProviders.getNatEventData(event).getRowPosition();
natTable.doCommand(new DeleteRowCommand(natTable, rowPosition));
}
});
}
})
.build();
Using this you don't need to call NatTable#refresh() because the command handler fires a RowDeleteEvent. I also don't suggest to call NatTable#refresh() in such a case, as it might change and refresh more than it should and would not update other states correctly, which is done correctly by firing the RowDeleteEvent.
Note that the shown example deletes the row for which the context menu is opened. If all selected rows should be deleted, you should create a command handler that knows the SelectionLayer and retrieve the selected rows as shown in the other answer.
In our application we do the following:
Get selected row objects:
SelectionLayer selectionLayer = body.getSelectionLayer();
int[] selectedRowPositions = selectionLayer.getFullySelectedRowPositions();
Vector<Your Model Objects> rowObjectsToRemove = new Vector<Your Model Objects>();
for (int rowPosition : selectedRowPositions) {
int rowIndex = selectionLayer.getRowIndexByPosition(rowPosition);
rowObjectsToRemove .add(listDataProvider.getRowObject(rowIndex));
}
Remove them from the data provider
call natTable.refresh()

Gwt sencha grid(requestfactory) not displaying data even when store has data

I have a sencha grid and it has a requestfactory to pull the data.
I can pull the data from the server but it does not show up.
I need to be able to make 2 selections from comboboxes and click a button to reload the grid. but it does not seem to work.
Here is the code -
#Override
public Widget asWidget() {
final ExplorerRequestFactory rf = GWT
.create(ExplorerRequestFactory.class);
rf.initialize(new SimpleEventBus());
RequestFactoryProxy<FilterPagingLoadConfig, PagingLoadResult<FlowerProxy>> proxy = new RequestFactoryProxy<FilterPagingLoadConfig, PagingLoadResult<FlowerProxy>>() {
#Override
public void load(
final FilterPagingLoadConfig loadConfig,
final Receiver<? super PagingLoadResult<FlowerProxy>> receiver) {
FlowerRequest req = rf.flowerRequest();
List<SortInfo> sortInfo = createRequestSortInfo(req,
loadConfig.getSortInfo());
req.getFlowers(vId, fId, loadConfig.getOffset(),
loadConfig.getLimit(), sortInfo).to(receiver);
req.fire();
}
};
loader = new PagingLoader<FilterPagingLoadConfig, PagingLoadResult<FlowerProxy>>(
proxy) {
#Override
protected FilterPagingLoadConfig newLoadConfig() {
return new FilterPagingLoadConfigBean();
}
};
loader.setRemoteSort(true);
FlowerProxyProperties props = GWT.create(FlowerProxyProperties.class);
ListStore<FlowerProxy> store = new ListStore<FlowerProxy>(props.id());
loader.addLoadHandler(new LoadResultListStoreBinding<FilterPagingLoadConfig, FlowerProxy, PagingLoadResult<FlowerProxy>>(
store) {
#Override
public void onLoad(
final LoadEvent<FilterPagingLoadConfig, PagingLoadResult<FlowerProxy>> event) {
LOG.info("Loader:addloadHondaler");
super.onLoad(event);
view.getView().refresh(false);
view.getView().layout();
//********Data successfully retrieved but does not populate the grid *********///
//**************************///
LOG.info("onLoad size:" + view.getStore().size()); //Data is present
}
});
final PagingToolBar toolBar = new PagingToolBar(50);
toolBar.getElement().getStyle().setProperty("borderBottom", "none");
toolBar.bind(loader);
ColumnConfig<FlowerProxy, String> nameColumn = new ColumnConfig<FlowerProxy, String>(
props.name(), 150, "Name");
ColumnConfig<FlowerProxy, Date> dateColumn = new ColumnConfig<FlowerProxy, Date>(
props.LastAccessDate(), 150, "Date");
dateColumn.setCell(new DateCell(DateTimeFormat
.getFormat(PredefinedFormat.DATE_SHORT)));
List<ColumnConfig<FlowerProxy, ?>> l = new ArrayList<ColumnConfig<FlowerProxy, ?>>();
l.add(nameColumn);
l.add(dateColumn);
ColumnModel<FlowerProxy> cm = new ColumnModel<FlowerProxy>(l);
view = new Grid<FlowerProxy>(store, cm);
view.getView().setForceFit(true);
view.setLoadMask(true);
view.setLoader(loader);
// Create the filters, and hook them to the loader and grid
GridFilters<FlowerProxy> filters = new GridFilters<FlowerProxy>(loader);
filters.initPlugin(view);
filters.addFilter(new DateFilter<FlowerProxy>(props.LastAccessDate()));
filters.addFilter(new StringFilter<FlowerProxy>(props.name()));
VerticalLayoutContainer con = new VerticalLayoutContainer();
con.setBorders(true);
con.setPixelSize(400, 300);
con.add(view, new VerticalLayoutData(1, 1));
con.add(toolBar, new VerticalLayoutData(1, -1));
return con.asWidget();
}
//********Call to this function should trigger a data pull and populate the grid ******///
/****************/
// Requestfactory call goes through, gets the data too but does not update the grid
public void reload(final String v, final String flower) {
LOG.info("V=> " + v + "\tFlower=> " + flower);
this.vId = v;
this.fId = flower;
LOG.info("Store size:" + view.getStore().size());
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
#Override
public void execute() {
if (v != null && flower != null && v.length() > 0
&& flower.length() > 0) {
loader.load();
LOG.info("Loader called");
}
}
});
}
Any ideas what I am missing here?
Without being able to run the code (as you didn't post the proxy, the server entity, the service proxy (aka request), or the service implementation, its a little hard to say, but I do see at least one thing definitely wrong, and others that may be confusing.
First and foremost, return the same instance from asWidget() each time it is called. The chain of events I am guessing is occurring that is confounding you:
App starts, something creates an instance of the widget where this asWidget method exists. In the course of setting it up, a store is created, as is a loader, and this.loader is assigned to that loader. The widget is added to the dom.
At some point, asWidget() is called a second time. This leaves the old grid attached (from the first time it was called), and creates a new grid, a new store, a new loader (and assigns to this.loader), but may not do anything with that new grid
Finally reload is called. This has a valid loader (the new one, not the old one), calls the server, populates the new store, which draws in the new grid. However, the old grid is still attached, so data never shows up.
With this fixed, you don't actually need to override any methods in LoadResultListStoreBinding - the base class will add items to the store, and the store will issue events that the grid is listening for.

Gwt Simple pager issues with a column sort handler

I have set up an AsyncDataProvider for my CellTable and added it to a SimplePager. I have hooked up a ListHandler to take care of sorting based on a column.
When I click the header of that column, the data doesn't change but on going to the next/previous page within the pager the data is then sorted. Also before the column is clicked there is no visual indicator on the column that would indicate that it is meant to be sortable.
How can I get the data to update when I click the header of the Column?
Here's my code snippet
service.getHosts(environment, new AsyncCallback<Set<String>>() {
#Override
public void onSuccess(final Set<String> hosts) {
final List<String> hostList = new ArrayList<String>(hosts);
//Populate the table
CellTable<String> hostTable = new CellTable<String>();
TextColumn<String> hostNameColumn = new TextColumn<String>(){
#Override
public String getValue(String string){
return string;
}
};
NumberCell numberCell = new NumberCell();
Column<String, Number> lengthColumn = new Column<String, Number>(numberCell){
#Override
public Number getValue(String string) {
return new Integer(string.length());
}
};
AsyncDataProvider<String> dataProvider = new AsyncDataProvider<String>() {
#Override
protected void onRangeChanged(HasData<String> data) {
int start = data.getVisibleRange().getStart();
int end = start + data.getVisibleRange().getLength();
List<String> subList = hostList.subList(start, end);
updateRowData(start, subList);
}
};
// Hooking up sorting
ListHandler<String> columnSortHandler = new ListHandler<String>(hostList);
columnSortHandler.setComparator(lengthColumn, new Comparator<String>(){
#Override
public int compare(String arg0, String arg1) {
return new Integer(arg0.length()).compareTo(arg1.length());
}
});
hostTable.setPageSize(10);
hostTable.addColumnSortHandler(columnSortHandler);
hostTable.addColumn(hostNameColumn,"Host Name");
lengthColumn.setSortable(true);
hostTable.addColumn(lengthColumn, "Length");
VerticalPanel verticalPanel = new VerticalPanel();
SimplePager pager = new SimplePager();
pager.setDisplay(hostTable);
dataProvider.addDataDisplay(hostTable);
dataProvider.updateRowCount(hosts.size(), true);
verticalPanel.add(hostTable);
verticalPanel.add(pager);
RootPanel.get().add(verticalPanel);
}
#Override
public void onFailure(Throwable throwable) {
Window.alert(throwable.getMessage());
}
});
I'm not sure how to make sure that the list is shared by both the table and the Pager. Before adding the pager I was using
ListDataProvider<String> dataProvider = new ListDataProvider<String>();
ListHandler<String> columnSortHandler = new ListHandler<String>(dataProvider.getList());
The AsyncDataProvider doesn't have the method getList.
To summarize I want the data to be sorted as soon as the column is clicked and not after I move forward/backward with the pager controls.
As per the suggestion I have changed the code for the AsyncDataProvider to
AsyncDataProvider<String> dataProvider = new AsyncDataProvider<String>() {
#Override
protected void onRangeChanged(HasData<String> data) {
int start = data.getVisibleRange().getStart();
int end = start + data.getVisibleRange().getLength();
List<String> subList = hostList.subList(start, end);
// Hooking up sorting
ListHandler<String> columnSortHandler = new ListHandler<String>(hostList);
hostTable.addColumnSortHandler(columnSortHandler);
columnSortHandler.setComparator(lengthColumn, new Comparator<String>(){
#Override
public int compare(String v0, String v1) {
return new Integer(v0.length).compareTo(v1.length);
}
});
updateRowData(start, subList);
}
};
But there is no change in the behavior even after that. Can someone please explain the process. The GWT showcase app seems to have this functionality but how they've done it isn't all that clear.
When using an AsyncDataProvider both pagination and sorting are meant to be done on the server side. You will need an AsyncHandler to go with your AsyncDataProvider:
AsyncHandler columnSortHandler = new AsyncHandler(dataGrid) {
#Override
public void onColumnSort(ColumnSortEvent event) {
#SuppressWarnings("unchecked")
int sortIndex = dataGrid.getColumnIndex((Column<Entry, ?>) event.getColumn());
boolean isAscending = event.isSortAscending();
service.getPage(0, sortIndex, isAscending, new AsyncCallback<List<Entry>>() {
public void onFailure(Throwable caught) {
}
public void onSuccess(List<Entry> result) {
pager.setPage(0);
provider.updateRowData(0, result);
}
});
}
};
dataGrid.addColumnSortHandler(columnSortHandler);
Clicking on a column header will then fire a columnSortEvent. Then you have to get the column clicked. I am overloading my servlet to provide both sorting and pagination, so I pass a -1 for the column index when only pagination is desired.
provider = new AsyncDataProvider<Entry>() {
#Override
protected void onRangeChanged(HasData<Entry> display) {
final int start = display.getVisibleRange().getStart();
service.getPage(start, -1, true, new AsyncCallback<List<Entry>>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(List<Entry> result) {
provider.updateRowData(start, result);
}
});
}
};
provider.addDataDisplay(dataGrid);
provider.updateRowCount(0, true);
Then your servlet implementation of getPage performs the sorting and pagination. The whole thing is much easier to follow with separate event handlers.
I think the problem is with the ListHandler initialization. You are passing hostList as a parameter to List Handler and in onRangeChange method you are calling updateRowData with a different list (sublist).
Make sure you use the same list in both the places.
or
Move your ListHander initialization and cellTable.addColumnSortHandler method call to onRangeChange method after updateRowData call.

Creating custom ActionCell in CellTable Column

I want one of my table columns to have a deleteButton.
ActionCell<Entrata> deleteCell = new ActionCell<Entrata>("x",new Delegate<Entrata>() {
#Override
public void execute(Entrata object) {
// rpc stuff....
}
});
Ok but this line generates an error:
Column<Entrata,Entrata> deleteColumn = new Column<Entrata, Entrata>(deleteCell);
"Cannot instantiate the type Column"
What do you think?
Here you go with working code:
Assumptions:
TYPE - Is the class of the data you show in rows of Cell Table it the same because I assume you want reference to the instance of data when you going to delete it
public class DeleteColumn extends Column<TYPE, TYPE>
{
public DeleteColumn()
{
super(new ActionCell<TYPE>("Delete", new ActionCell.Delegate<TYPE>() {
#Override
public void execute(TYPE record)
{
/**
*Here you go. You got a reference to an object in a row that delete was clicked. Put your "delete" code here
*/
}
}));
}
#Override
public TYPE getValue(TYPE object)
{
return object;
}
};
From the doku:
A representation of a column in a table. The column may maintain view data for each cell on demand. New view data, if needed, is created by the cell's onBrowserEvent method, stored in the Column, and passed to future calls to Cell's
So you have to declar it something like this:
Column<String, String> colum = new Column<String, String>(null) {
#Override
public String getValue(String object) {
// TODO Auto-generated method stub
return null;
}
};
Still I don't exactly know how you implement the delete button, so it would be nice if you can give us the rest of your code.
This works
//table = initialized CellTable with content already loaded
ActionCell editCell = new ActionCell<EmployeeObject>("remove", new ActionCell.Delegate<EmployeeObject>() {
public void execute(EmployeeObject object){
List<EmployeeObject> list = new ArrayList<EmployeeObject>(table.getVisibleItems());
for(int i = 0; i < list.size(); i ++){
if(object.getFirstname().equals(list.get(i).getFirstname())){
list.remove(i);
break;
}
}
table.setRowData(list);
}
});
Column<EmployeeObject, ActionCell> editColumn = (new IdentityColumn(editCell));