How do I prevent a CellTable RowElement from being redrawn after a SelectionChangehander fires? - gwt

I'm probably doing something else wrong but I've followed examples given here:
How to remove a row from the Cell Table
and
GWT get CellTable contents for printing or export
to accomplish my goal and the result is close but not quite right.
I have a page with two widgets. The first wiget contains a CellTable that uses an aSync ListDataProvider to pull results and populate a table. The table has a selection change event handler associated with it that loads further details about the selected item into the second widget below it.
public OrderAdminTable() {
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
#Override
public void onSelectionChange(SelectionChangeEvent event) {
OrderAdminListProxy selected = selectionModel.getSelectedObject();
if (selected != null && orderSnapShot != null) {
orderSnapShot.loadSnapShot(selected);
}
}
});
initTable();
this.addStyleName("order-list fixed_headers BOM");
this.setSelectionModel(selectionModel);
}
Once the second widget has loaded the details about the selected item, the user can remove the item from the table/list by clicking a button in the RootPanel that is the parent of both widgets.
searchView.getCmdReview().addClickHandler(new ClickHandler() {
#Override public void onClick(ClickEvent event) {
searchView.getOrderAdminSnapshot().reviewOrder();//this line calls a web service that deletes the item from the server data
dataProvider.getList().remove(searchView.getOrderAdminSnapshot().getSelectedOrder());
for(int i=0;i<table.getRowCount();i++){
TableRowElement row = table.getRowElement(i);
for(int j=0;j<row.getCells().getLength();j++){
if(row.getCells().getItem(j).getInnerText().contains(searchView.getOrderAdminSnapshot().getSelectedOrder().getSalesOrderNumber())){
row.setAttribute("removed", "true");
row.addClassName("hidden");
}
}
}
}
});
This all works fine until you select another item in the table. When that happens, the selection change event seems to redraw the table and remove my custom attribute and class from the previously selected item. This makes it appear in the list again.
The ultimate goal here is to avoid a round trip to the server to pull new results when you remove an item from the list. The line "searchView.getOrderAdminSnapshot().reviewOrder();" makes a web service call that removes the item from the data on the server side so it does not appear in subsequent reloads.
Is there some way to force the selection change event to maintain the state of the table row that was previously selected? Is there a better way to remove the selected item from the list? Any advice would be appreciated.

Once you remove the object from the list dataProvider.getList().remove, it should disappear from the table. There is no need to hide the row - this row should be gone. So your loop should never find it.

Related

GWT CellTable rebuilding rows unnecessarily

I have found an interesting issue, and I am wondering if I am misusing or overlooking something. I have a large CellTable that is vertically scrollable. I want to show all the rows at once instead of traditional pagination. So at the bottom of my table I have a row that the user can click to load 50 more rows. I have provided the table with a custom table builder (setTableBuilder(new Builder());). When the user clicks "load more" I query the data, add to the ListDataProvider and call table.setVisibleRange(0, dataProvider.getList().size());.
I put a log statement in the
#Override
public void buildRowImpl(Object rowValue, int absRowIndex) {
}
method to see when it was building rows. I notice that it would build 0-dataProvider.getList().size() (all the rows), then it would build oldLength-dataProvider.getList().size() (the new rows). For instance, if I have 100 rows and then load 50 more it would build 0-150, and then rebuild 100-50. What I want is for it to only build the new rows, obviously.
So I start debugging to see why it is rebuilding the whole table each time. What I found was in com.google.gwt.user.cellview.client.HasDataPresenter it would set the "redrawRequired" flag to true at line 1325:
else if (range1 == null && range0 != null && range0.getStart() == pageStart
&& (replaceDiff >= oldRowDataCount || replaceDiff > oldPageSize)) {
// Redraw if the new data completely overlaps the old data.
redrawRequired = true;
}
So my question is why does it think that the new data completely overlaps the old data?
Am I using something incorrectly, is there a better way? This gets to be quite a slow down when it has to redraw thousands of rows that don't need to be redrawn.
Thanks,
Will
I think that, in this situation, the only way a CellTable can react to the call of the setVisibleRange() method is to redraw all rows.
You have just informed a CellTable that now it has to display new range (0-150 rows) instead of last (0-100 rows). There is no information that rows 0-100 remain unchanged and there is no need to redraw them.
The interesting thing is that you found the new rows are updated (rebuild) twice:
For instance, if I have 100 rows and then load 50 more it would build 0-150, and then rebuild 100-50
I've tried to reproduce this behavior in the smallest example:
public class ListDataProviderTest implements EntryPoint {
private static final int ADD_COUNT = 10;
private int nextVal = 0;
public void onModuleLoad() {
final CellTable<Integer> cellTable = new CellTable<Integer>();
cellTable.addColumn(new TextColumn<Integer>() {
#Override
public String getValue(Integer object) {
return object.toString();
}});
final ListDataProvider<Integer> listDataProvider = new ListDataProvider<Integer>();
listDataProvider.addDataDisplay(cellTable);
RootPanel.get().add(cellTable);
RootPanel.get().add(new Button("Add more...", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
List<Integer> list = listDataProvider.getList();
for(int i = 0; i < ADD_COUNT; i++)
list.add(nextVal++);
cellTable.setVisibleRange(0, list.size());
}
}));
}
}
But I get all the rows updated once.
Can you confirm that this example reproduces the issue or provide one that is more accurate?
AFAIK a CellTable always redraws all cells.
This is how the renderer from the CellTable works. Although it always redraws all cells, it is in most times still faster than using a FlexTable and only updating a few cells.

How to don't validate form with Ajax buttons

I have a problem with validation on form actually sub-form.
In my website I have some kind of table and "Add row" button (BlockingAjaxSubmitLink).
When I try add let say 2 rows, I get validation error (because row in this table has Required=True parameter) and I can't add another row. I tried use simple AjaxLink but it doesn't have reference to form in onClick method and when I complete some rows and click "Add row" this data get lost.
I want to enable validation only after "save" button click.
Any idea how to deal with this problem?
I do something like you want using an AjaxLink.
My AjaxLink:
private AjaxLink addNewRow = new AjaxLink("addNewRow") {
#Override
public void onClick(AjaxRequestTarget target) {
MyEntityObject newTableRowObject = new MyEntityObject(irrelevantParameter);
entityObjectTableService.createNewRowInDB(newTableRowObject );
target.add(listViewContainer);
}
};
In this code the listViewContainer is a WebMarkupContainer which contains a ListView holding the table rows.
When i click this AjaxLink a new object representing a row in my table is added to the database and then the container containing the ListView is being refreshed refreshing the ListView and the new empty object is being fetched from the DB and shown as a new row in my table at the end.
Depending on your structure maybe you are looking after disabling validation using setDefaultFormProcessing(true); - http://ci.apache.org/projects/wicket/apidocs/6.x/org/apache/wicket/markup/html/form/AbstractSubmitLink.html#setDefaultFormProcessing%28boolean%29
For now I write some kind of hack
First I set
addKnowledgeLink.setDefaultFormProcessing(false);
and next
BlockingAjaxSubmitLink<Object> addKnowledgeLink = new BlockingAjaxSubmitLink<Object>(
"link_knowledge_add") {
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ChangeDataForm.this.process(this);
/* some code */
target.add(form.get(MY_CONTAINER_ID));
}
(...)
and my hack...
//HACK
public void process(IFormSubmitter object){
if (!isEnabledInHierarchy() || !isVisibleInHierarchy())
{
return;
}
// run validation
validate();
/*if (hasError())
{
// mark all children as invalid
markFormComponentsInvalid();
// let subclass handle error
callOnError(object);
}
else
{*/
// mark all children as valid
markFormComponentsValid();
// before updating, call the interception method for clients
beforeUpdateFormComponentModels();
// Update model using form data
updateFormComponentModels();
// validate model objects after input values have been bound
onValidateModelObjects();
if (hasError())
{
callOnError(object);
return;
}
// Form has no error
delegateSubmit(object);
//}
}
and I ovveride one method
#Override
protected void onError(){
super.onError();
this.updateFormComponentModels();
}
I know it is ugly solution but I couldn't figure out anything better..
And I couldn't shutdown feedback messages

Radio button change handler refreshing the page

I'm using UploadItem, RadioGroupItem and some other widgets. RadioButton is having onChangeHandler which will decide what all other components need to be displayed. I've uploaded some file using UploadItem. Then I changed the radio button selection. On changing the radio button, required widgets are getting displayed properly but whatever file I'd selected using UploadItem is going away. Fresh UploadItem widget is getting displayed. In other words page is getting refreshed.
My requirement is whenever I change radio button option, required widget should displayed along with that whatever file I had selected using UploadItem should remain same.
My Code is something like this:
UploadItem upload = new UploadItem();
RadioGroupItem radioGroup = new RadioGroupItem();
HashMap map = new HashMap();
map.put("option1","option1");
map.put("option2","option2");
radioGroup.setValueMap(map);
TextItem textbox = new TextItem();
radioGroup.addChangeHandler(new ChangeHandler(){
public void onChanged(ChangedEvent event) {
String radioValue =((String)event.getValue());
if(radioValue.equalsIgnoreCase("option2")){
textbox.show();
}else{
textbox.hide();
}
}
});
Add all created widgets to DynamicForm object using dynamicForm.setFields(all created widgets)
Changing the radio button should hide and show the textBox. But while doing that page is getting refreshed and whatever file we had selected using UploadItem is lost.
As per the documentation for hide() and show() of FormItem class, invocation of any of these methods, will cause the DynamicForm to be redrawn.
So it may cause the problem you're getting.
To overcome this issue, I would suggest you to put UploadItem in a separate DynamicForm.
fire an event on radio Selection change as
radioButton.addListener(Events.Change, new Listener<BaseEvent>() {
#Override
public void handleEvent(BaseEvent be) {
if(radioButton.getValue()){
//fire an event here for ur widget
}
}
});

On click functionality of Button Inside ListView in Wicket Framework

Im populating a table using ListView component in wicket.The last column of my table is button. So for each row I'll have a button in the last column.What I'm trying to implement is onlick of the button I need to delete the appropriate row. So for this I need to get the current index of the list on click of button. How to achieve/get this ?
I would extend Ajax button and pass the row reference (item) in the constructor...then you can do anything you want..by overriding the onSubmit method
Example:
private class SpecialButton extends AjaxButton {
final Item<Object> rowItem;
public SpecialButton(final String id, final Item<Object> rowItem) {
super(id);
this.rowItem = rowItem;
}
#Override
protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
// here you cand do everything you want with the item and the model object of the item.(row)
Object object = rowItem.getModelObject();
}
}
You should replace Object from Item<Object> with your reapeater model. After creating this private class you can reuse it for every row in your repeater.
If you want to delete that row you just have to remove the model from the list used to generate the repeater and refresh the repeater container(Wicket does not allow you to refresh the repeater by adding it to the target...instead you have to add the repeater continer.)
Have a look at the repeaters Wicket Examples page to understand how to use ListView and other repeaters:
http://www.wicket-library.com/wicket-examples/repeater/
You can get the current index of the list from item.getIndex()
protected void populateItem(final ListItem<T> item) {
int index = item.getIndex();
...
Look here for inspirations on how to do it properly (without index):
Wicket ListView not refreshing

GWT CellTable keep focus on selected row

When I select a row in a CellTable which contains several columns, the whole row gets colored in yellow. It does not depend on which area of the row I click (which column of the row).
What I try to do is to keep the selected row colored in yellow as long as no other row of this very table is selected. At the moment, as soon as I click somewhere else in the browser, the row gets back its original color.
I tried to use a selection model, but this changed nothing. Do you have any advise or is this simply not possible, since the focus is managed by the browser? The behavior is the same in the Google showcase for the CellTable...
The selection model actually does what you want to do: it paints a row blue and the row does not change color if you click elsewhere in the page. (Only when another row is selected)
There are 2 selection models:
One that lets you select only one row, and another one that lets you select multiple rows.
MultiSelectionModel<Row> selectionModel = new MultiSelectionModel<Row>();
table.setSelectionModel(selectionModel);
SingleSelectionModel<Row> selectionModel = new SingleSelectionModel<Row>();
table.setSelectionModel(selectionModel);
The solution of user905374 did actually work. I mentioned in my first post that I already tried the solution with a selectionModel and that it did not work. This was partially true. It does work, but only if the table does NOT contain a CheckboxCell.
Following a working and the not working example. I think this might be a bug, but I am not sure if I miss something.
final CellTable<LicenceDto> licenseTable = new CellTable<LicenceDto>();
final SingleSelectionModel<LicenceDto> selectionModel = new SingleSelectionModel<LicenceDto>();
licenseTable.setSelectionModel(selectionModel);
//--- If I add this column, the selection does work.
Column<LicenceDto, String> workingColumn = new Column<LicenceDto, String>(new TextCell()) {
#Override
public String getValue(LicenceDto object) {
return "Works";
}
};
workingColumn.setFieldUpdater(new FieldUpdater<LicenceDto, String>() {
#Override
public void update(int index, LicenceDto object, String value) {
;
}
});
licenseTable.addColumn(workingColumn);
//--- If I add this column, the selection does NOT work anymore.
Column<LicenceDto, Boolean> notWorkingColumn = new Column<LicenceDto, Boolean>(new CheckboxCell(true, true)) {
#Override
public Boolean getValue(LicenceDto object) {
return object.getEnabled();
}
};
notWorkingColumn.setFieldUpdater(new FieldUpdater<LicenceDto, Boolean>() {
#Override
public void update(int index, LicenceDto object, Boolean value) {
presenter.enableLicense(object, value);
}
});
licenseTable.addColumn(notWorkingColumn);
You can even combine multiple cells and add them to the table (e.g. LinkActionCell etc). As long as there is no CheckboxCell, the blue selection with the SingleSelectionModel does work like a charm. Does anyone see what I do wrong with this CheckboxCell or is there a bug?
UPDATE
It was simply a usage error of me. The problem was that I set handlesSelection to true (second parameter of the CheckboxCell constructor) even thought I don't handle anything. Setting it to false solves the problem.
Bottomline: Use a selection model (e.g. SingleSelectionModel) and do not set the handlesSelection parameter to true of the CheckboxCell constructor to true, if you don't handle the selection by yourself.
You should observe the Showcase demo again. This time use the checkbox on the left most column i.e the first column. On selection the row turns blue indicating the row selection is made. This is when you have SelectionModel set up. Click on the page anywhere outside the CellTable/DataGrid the selection is not changed.
Now, instead of choosing the row via checkbox from first column, you click on a row in any other column. The row turns yellow. Click on the page anywhere outside the CellTable/DataGrid the focus/yellow is lost.
"colored in yellow" indicates row is under focus and being edited and not selected.
Note - you can force row selection by using click events per cell.
Try something like this:
CellTable table;
YourDataObject object = new YourDataObject(...);
SingleSelectionModel<YourDataObject> selectionModel =
new SingleSelectionModel<YourDataObject>();
table.setSelectionModel(selectionModel);
...
table.setSelected(object, true);
Use MultiSelectionModel if you wish more than one line to be highlighted.
Store the selected row's index. When user selects row, change row's style to some "selected-style" appropriate for your case (defined in your css file) and remove selected style from the previously selected row. Also don't forget to update selected row's index.
If you provide some code from the original version I help you out with some code with pleasure.