Working with GXT(Ext GWT) Grid : Create an Editable Grid

Last week i was so busy that i can not afford to manage time on writing. And i am afraid that whether i can keep my promise on writing a series of tutorials about GXT and GWT or not. In the upcoming days i have to work in six! projects simultaneously. Good thing is that there will be a lot of new things that i can learn and surely i will share those here whenever i get time. Now i will show you how you can make a GXT Grid editable with TextField, ComboBox and Date Picker.

Create a new project named GxtEditableGrid and add GXT library in the project. As like my previous blogs about GXT Grid i have used the same Employee model and TestData class for generating data. You will find the code of these classes here. Go to the onModuleLoad method of GxtEditableGrid class and remove all the auto generated code of this method.

Starting with creating a list of ColumnConfig and a ColumnConfig instance named column. Configure this column to show and edit Employee Name first. To add the editing functionality create a TextField and a CellEditor with this TextField. Then set the CellEditor as the editor of the column.

List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
ColumnConfig column = new ColumnConfig();
column.setId("name");
column.setHeader("Employee Name");
column.setWidth(200);
TextField<String> text = new TextField<String>();  
text.setAllowBlank(false);  
text.setAutoValidate(true);  
column.setEditor(new CellEditor(text));
configs.add(column); 



For the Department column rather than using a TextField we are going to use a ComboBox to edit this field. First create a SimpleComboBox and add the possible values to it.

final SimpleComboBox<String> combo = new SimpleComboBox<String>();  
combo.setTriggerAction(TriggerAction.ALL);  
combo.add("General Administration");  
combo.add("Information Technology");  
combo.add("Marketing");  
combo.add("Accounts"); 

Then create a CellEditor with the SimpleComboBox and set it as the editor of the department column.

CellEditor editor = new CellEditor(combo) {  
@Override  
public Object preProcessValue(Object value) {  
if (value == null) {  
return value;  
}  
return combo.findModel(value.toString());  
}  

@Override  
public Object postProcessValue(Object value) {  
if (value == null) {  
return value;  
}  
return ((ModelData) value).get("value");  
}  
};  

column = new ColumnConfig("department", "Department", 150);
column.setAlignment(HorizontalAlignment.LEFT);
column.setEditor(editor);  
configs.add(column);

For the Designation column configure it like the Employee Name column and for the Salary column set a cell editor with NumberField. That is this field will only accept numeric values.

column = new ColumnConfig("designation", "Designation", 150);
column.setAlignment(HorizontalAlignment.LEFT);
TextField<String> text2 = new TextField<String>();  
text2.setAllowBlank(false);  
text2.setAutoValidate(true);  
column.setEditor(new CellEditor(text2));
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>";
}  
};  
column.setRenderer(checkSalary); 
column.setEditor(new CellEditor(new NumberField()));  
configs.add(column);

To change date field in a Grid with date picker create a DateField, set a date fomat for the DateField and finally set this as the editor for the ColumnConfig.

DateField dateField = new DateField();  
dateField.getPropertyEditor().setFormat(DateTimeFormat.getFormat("MM/dd/y"));

column = new ColumnConfig("joiningdate", "Joining Date", 100);
column.setAlignment(HorizontalAlignment.RIGHT);
column.setEditor(new CellEditor(dateField));  
column.setDateTimeFormat(DateTimeFormat.getMediumDateFormat());
configs.add(column);

To enable the editable functionality of grid you have to create an instance of EditorGrid class instead of a Grid class now. Other things are described in my previous tutorials about GXT Grid.

ListStore<Employee> employeeList = new ListStore<Employee>();
employeeList.add(TestData.getEmployees());
ColumnModel cm = new ColumnModel(configs);

final EditorGrid<Employee> grid = new EditorGrid<Employee>(employeeList, cm);
grid.setStyleAttribute("borderTop", "none");
grid.setAutoExpandColumn("name");
grid.setBorders(true);
grid.setStripeRows(true);

ContentPanel cp = new ContentPanel();
cp.setBodyBorder(false);
cp.setHeading("Employee List");
cp.setButtonAlign(HorizontalAlignment.CENTER);
cp.setLayout(new FitLayout());
cp.setSize(700, 300);
cp.add(grid);
RootPanel.get().add(cp);

That's all. Run the application check the magic GXT. To view the live demo of this tutorial Click here.

editableGrid

50 comments:

Anonymous February 1, 2010 at 2:35 AM  

thank you, this helped a lot!

Anonymous February 5, 2010 at 12:00 PM  

Good one.
I have a question.

I'm actually trying to implement a grid with columns such as name, value in a UI in my application.

For certain values, I should put a drop down box and for others I should put text field in 'value' column.

Is it possible to add different types of widgets to the same column in a grid?
Thanks.

Unknown February 6, 2010 at 12:05 AM  

yes, it is possible to add different widgets in same column. Create a GridCellRenderer object which will return different widgets on different conditions. Then set this object in the setRenderer method of your column.

Anonymous April 27, 2010 at 7:13 AM  

really helpful

i have some doubts
1.Is there any way I can add or remove rows in grid on click of some button?
2.What is the substitute of flex table(provided by GWT)in GXT?

Unknown April 30, 2010 at 12:11 AM  

Yes it is possible to add or remove rows in grid by simply clicking on a button. In the click handler of the button just write this

//to add
yourListStore.add(yourModel);

//to remove
yourListStore.remove(yourModel);

I am not sure whether there exists a substitute for GWT Flex Table in GXT or not.

salvin May 28, 2010 at 8:48 PM  

hi,
I am using an editor grid in my project.

The UI works fine, but when i need to save the values back to the database, the store returns back the initial values and not the user modified values.

I even called the method store.commitChanges(); and it still returns the initial values.

I have used a simple text field as a cell editor.

Unknown May 28, 2010 at 9:07 PM  

@Salvin: If you want to save the values in database you have done it by yourself, gxt doesn't support it. You have to call an rpc method and reload the store. The commitChanges() method applies only on the local store not on the database.

salvin May 28, 2010 at 11:21 PM  

maybe you have misunderstood me,

I need to SEND the changed value to the server.


As mentioned in my post:
"the store returns back the initial values and not the user modified values."



How can i send value to the server if i dont get changed value ??

eg: grid contains value 100
user changes it to 30

When I read the store, it gives me 100 not 30.

Unknown June 3, 2010 at 11:57 PM  

@Salvin: Sorry for misunderstanding you :-( I have done something similar to your task. But haven't face any problem. Can you please provide me the code?

Kim Huang June 26, 2010 at 12:53 PM  

this is the task which I am working on, I have an EditorGrid in client side which shows the data from server side - fetched by RPC call, the user change some values of the columns of EditorGrid, then I will send the change back to server and server made some operation on the data and send the data back to the client, I will show the newly change(response from server) in the EditorGrid, I thought it is a very typical case, but where I can find the example or tutorial which is similar to my task ?

Anonymous July 2, 2010 at 12:07 AM  

I have a requirement of Creating Dynamic editable columns.The columns are getting created
If I use the CellEditor in static Column, It is becoming editable. But for the Dynamic Column, The column is not becoming editable.
Neither any exception is thrown.
I am unable to figure out what is happening exactly.

Angel Lacret July 9, 2010 at 6:39 AM  

I'm having the same problem with SAVE the changes made in the grid, i put the Store Listener as it was made to be, but, the StoreEvent returns the fields unmodified... even if i call store.commitChanges() after the operation... can anyone please help us?

vandana August 6, 2010 at 2:40 AM  

I am using Ext-gwt.I have to export grid data to excel/Pdf.Has anyone done this? Please help me.
It will be great help for me....

Unknown August 6, 2010 at 6:17 AM  
This comment has been removed by the author.
Unknown August 6, 2010 at 6:25 AM  

@Vandana: I have exported grid data to Excel using JExcelApi

Keith B August 27, 2010 at 10:15 AM  

I have a question, I'm creating an editable grid with two columns. Name and Sequence. The name remains uneditable but sequence is editable. I want to create a button which clears the values in the sequence column ONLY, but allows me to reject those changes with a Cancel button is pressed afterwards, and then returns the previous values. Is this possible?

Unknown August 27, 2010 at 7:33 PM  

@Keith: you can use listStore.rejectChanges();
and listStore.commitChanges(); to
gain your desired functionality.

Keith B August 30, 2010 at 7:56 AM  

That's not quite what I'm asking. Maybe I described it incorrectly. The desired functionality of the button is the clear the values in every cell in a column. To clear the cells completely but only in one specific column. However, if they click the cancel button, they can get the values that existed before they clicked the clear button. In other words, how can I clear all the values in one specific column, but not commit those changes to the store.

Example:

Name | Sequence
Bob 1
Jim 2
Karen 3

click "clear" button...

Name | Sequence
Bob
Jim
Karen


User decides nevermind clicks "cancel" button...

Name | Sequence#
Bob 1
Jim 2
Karen 3

Anonymous September 7, 2010 at 2:57 AM  

Hi.
I have the same problem of Salvin. My combobox doesn't return the user value modified, but it returns the initial value.
Someone can help me?
Thank you

M.P.Prabu October 26, 2010 at 1:15 AM  

I am new for Ext GWT.

Can u please help me how to create edior grid in Ext gwt.

with out Database I have to create the grid....

Help me for this....

M.P.Prabu October 26, 2010 at 1:17 AM  

I am new for the EXT GWT.

Can u please help me for Creating Editor Grid in EXT GWT with out database.

Please give me in Brief.

Unknown October 26, 2010 at 3:57 AM  

@M.P.Prabu : This tutorial can help you.

M.P.Prabu October 26, 2010 at 4:09 AM  

Thanks Shams Zawoad Ratul...

I already tried that way... But I am not able do that.... Can u please give me a simple way to create Editor Grid in Ext GWT.

Thanks in Advance.

Anonymous November 10, 2010 at 10:49 PM  

My requirement is to use same grid for several types of list (objects of different types).

As per the object type, I want to render a specific column with different icon/image.

As ColumnConfig's setRenderer is mentioned as pre-render, I am not able to render the column differently after the grid has been created.

Please guide me how to achieve this.

Unknown November 11, 2010 at 5:40 PM  

I have an idea. Try with this.

Create an Interface for the Object type. Add a method getType() in the interface.

All of your classes must implement this interface. Return different value from different classes.

Now you can use the getType method in the setRenderer code block to achieve your goal.

Anonymous November 11, 2010 at 9:26 PM  

The interface is there, method to return object type is also there.

Here the question is - can I render a column (setRenderer()) after the grid has been created.

Or, do I have to create the grid again and again, which is not that good.

Unknown November 13, 2010 at 6:19 PM  

If you have create the ListStore of Interface type then you don't have to create the grid again and again

Anonymous November 14, 2010 at 8:57 PM  

Thanks, that is absolutely perfect.

Unknown November 16, 2010 at 6:00 AM  

Welcome :)

morrismano February 10, 2011 at 10:08 PM  

Hi Shams,

I have a Requirement .left side i have a treepanel,which contains nodes.
A Treepanel with a root node as 'Artist' containing a list of 'Albums' .to the right side i have
A Grid Showing the list of songs for the selected Album on the Treepanel.below the grid i have A Content panel showing the details of the particular song selected on the grid.plz help me with this.

Anonymous March 28, 2011 at 7:45 AM  

Hi Shams,

Congratulations for your post! I have this same grid in my app, built with ColumnConfig[] array. One of these columns has an editor defined with a NumberField.

My problem is: I've added a FieldListenerAdapter in NumberField that must access one of the RecordDef[] element. The RecordDef was set as the store's reader of the grid. The type of the RecordDef is ObjectFieldDef.

Is it possible? Do I need to use getParent method?

Thanks a lot, guilherme

ashtrick April 6, 2011 at 1:20 AM  

Hi,

I need to add a button to the last column and perform some tasks on the row when someone clicks it.

How can I do that? How do I add a button? I can't find any CellEditor constructor that accepts a button.

Thanks in advance,
-ash

Unknown April 10, 2011 at 10:03 PM  

@ashly : use this code

GridCellRenderer<BaseModel> gridCellRenderer = new GridCellRenderer<BaseModel>() {

private boolean init;
public Object render(final BaseModel model, String property, ColumnData config, final int rowIndex,
final int colIndex, ListStore<BaseModel> store, Grid<BaseModel> grid) {
if (!init) {
init = true;
grid.addListener(Events.ColumnResize, new Listener<GridEvent<BaseModel>() {

public void handleEvent(GridEvent<BaseModel> be) {
for (int i = 0; i < be.getGrid().getStore().getCount(); i++) {
((Button) be.getGrid().getView().getWidget(i, be.getColIndex())).setWidth(be.getWidth() - 10);
}
}
});
}
final Button b = new Button("Complete");
b.addSelectionListener(new SelectionListener<ButtonEvent>()
{

@Override
public void componentSelected(ButtonEvent ce)
{
//write your action here
}
});
b.setWidth(grid.getColumnModel().getColumnWidth(colIndex) - 10);
b.setToolTip("Click To Complete");

return b;

}
};

Now set this renderer as the renderer of your ColumnConfig.

column.setRenderer(gridCellRenderer );

ashtrick April 15, 2011 at 1:24 AM  

Thanks Shams.. that works..!

-ashly

Unknown May 8, 2011 at 10:38 AM  

Hi,
I was using GXT's simple grid and fetching data from db and it was working fine for me.
Now I am trying to make it editable.
I made a simple change in the code like:
TextField text = new TextField();
column = new ColumnConfig("outward", "OUTWARD", 50);
column.setEditor(new CellEditor(text));
configs.add(column);

and changed the Grid to EditorGrid, but I am getting a run time exception as:
23:00:12.232 [ERROR] [rojettha] Uncaught exception escaped
java.lang.IllegalStateException: Should only call onDetach when the widget is attached to the browser's document

at the point where I am adding editor to column.
Please help.

Thanks,
Madhur

Unknown May 8, 2011 at 7:43 PM  

@madhur: If you are doing the RPC call for fetching data from db before building all the UI, move the RPC call to the end of the initialization routine.

Anonymous May 9, 2011 at 4:11 AM  

HEY I WAS USING THE SAME TEXTFIELD AS EDITOR FOR MORE THA ONE FILD AND IT CREATED THE PROBLEM.
USING DIFFERENT TEXTFILEDS SOLVED THE PROBLEM

THANKS,
MADHUR

Anonymous June 28, 2011 at 10:14 PM  

Please help me. I have a model with following properties: Type, Description, Amount, Comment Id, Comment Text.
I want to create an EditorGrid with three columns. First one shows Description (label. Not editable. Automatically generated when loaded from db), Second one is a Number Field (editable) and third one is a drop down to select one of predefined comments (they depend on the Type property of the model. So it needs to be dynamically populated. I have a complete HashMap available in hand which gives me the possible comments list(id/value) for a given Type). If the comment 'Other' (one of the options available in every drop down) is selected, I need to dynamically display a Text Box below that grid row, which should be bound the 'Comment Text' property of the model. I need some guidance for dynamically populate dropdown for every row and adding text field below the grid row. Thanks in advance.

Anonymous June 28, 2011 at 10:27 PM  

FYI, Type and Description both are automatically generated in db before client loads it.
Eg: (Type, Desc, Amt, CommId, CommTxt) values
('EL', 'Electronics', '0',null,'');
('AC', 'Accessories', '0',null,'');
('GA', 'Games','0',null,'');
.....

comments can be like (type, id/val)
EL - 1/ABC, 2/XYZ, 3/Other
AC - 4/DEF, 5/Other
GA - 6/EFG, 7/FGH, 8/GHI, 9/Other
.....

Suraj Shinde July 2, 2011 at 10:18 AM  

Hi Everyone.

I have 2 side by side grids used as drag and drop.The second grid is an editable grid with one column as ComboBox selection.With the help of examples i was able to get some constant list in the ComboBox drop down.But i want to set different data in Combo box for different rows in the grid.How this can be achieved.

Regards,
Suraj

chandra July 31, 2011 at 10:22 PM  

Hi Shams Zawoad Ratul,
Please could you share me the code to export grid data into multiple excel sheets.


Thanks,
David

Nagan August 1, 2011 at 1:23 PM  

i am also having the same as below issue which was posted 2 posting before please help "Please help me. I have a model with following properties: Type, Description, Amount, Comment Id, Comment Text.
I want to create an EditorGrid with three columns. First one shows Description (label. Not editable. Automatically generated when loaded from db), Second one is a Number Field (editable) and third one is a drop down to select one of predefined comments (they depend on the Type property of the model. So it needs to be dynamically populated. I have a complete HashMap available in hand which gives me the possible comments list(id/value) for a given Type). If the comment 'Other' (one of the options available in every drop down) is selected, I need to dynamically display a Text Box below that grid row, which should be bound the 'Comment Text' property of the model. I need some guidance for dynamically populate dropdown for every row and adding text field below the grid row. Thanks in advance."

narveen December 10, 2011 at 3:26 AM  

Creating Dynamic text fields/combobox in Editable grid

Hi All,

I am new to GWT and Ext-GWT(gxt-2.2.4.jar) . I am using EditorGrid and creating 3 columns, i have Combobox in first columns. and text field in second column, Now my question is If i select a value in Combobox based on the value i have to created the textfield/combobox in the second column.

Example: In first column combobox i have values like gender,Age . If i select Gender value in combobox then the second column should create a combobox drop down with Male,Female as values, If i select Age as value in first combobox drop down ,then the second column should create a text field.

Grid col 1 Grid Col 2
--------- ---------
|Gender|+ |Male|+ <-Combobox->
--------- |Female|

Grid Col 1 Grid Col 2
---------- ------------
|Age|+ |---|
|Gender|
Please give me a suggestion .....Thanks lot

wpeirone June 4, 2012 at 1:06 PM  

Hi, very usefull info.
I have to do a grid with edit capabilities. How I should do the cell editor to display the value, and when enter to edit mode display another in order to edit it (like excel with the formula).

Thanks,
Walter

Anonymous June 27, 2012 at 3:31 AM  

The information was very useful... thanks a lot. It helped me a lot. Thanks again....

Royalking June 30, 2012 at 12:55 PM  

using gxt 3 can i create a column with different widgets in it.
(column with button,checkbox and combobox)

Thanks in advance

novoace July 23, 2012 at 3:03 AM  

Hi all,

Is it possible to create and use some custom (and complex) cell editor?

For example - cell displays only file name as String but when you click editor should contain file upload and maybe some additional text input field.
If this is possible does anyone know of an example or tutorial how to create these custom editors??

Thanks

Anonymous September 9, 2013 at 9:24 AM  

hi;
pleaz how can I recuper the value of the item selected in the cell combobox

Anonymous December 10, 2013 at 10:37 PM  

HI,
Very helpful article.Good work

I have a scenario in my project wherein a simpleCombox is attached to cells of two different columns 'A' and 'B' and the values in a simpleCombox (B) should change dynamically(with help of SQL query from back-end) depending on a selection of value in another simpleCombox (A)..This should happen to each cell as a value selected in A can be different for different rows and subsequently the values in simpleComboBox(B) will be different.

Please suggest a solution

Unknown February 3, 2015 at 9:12 PM  

hi to the author, do you how to add gridEditor using DualListField?

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers