ExtJS and Spring MVC Framework: CRUD DataGrid Example
Posted on : 22-03-2010 | By : Loiane | In : ExtJS, Grid
35
This tutorial will walk through how to implement a CRUD (Create, Read, Update, Delete) DataGrid using ExtJS and Spring Framework.
What do we usually want to do with data?
- Create (Insert)
- Read / Retrieve (Select)
- Update (Update)
- Delete / Destroy (Delete)
Until ExtJS 3.0 we only could READ data using a dataGrid. If you wanted to update, insert or delete, you had to do some code to make these actions work. Now ExtJS 3.0 (and newest versions) introduces the ext.data.writer, and you do not need all that work to have a CRUD Grid.
So… What do I need to add in my code to make all these things working together?
In this example, I’m going to use JSON as data format exchange between the browser and the server.
First, you need an Ext.data.JsonWriter:
// The new DataWriter component.
var writer = new Ext.data.JsonWriter({
encode: true,
writeAllFields: false
});
Where writeAllFields identifies that we want to write all the fields from the record to the database. If you have a fancy ORM then maybe you can set this to false. For example. This is my record type declaration:
var Contact = Ext.data.Record.create([
{name: 'id'},
{
name: 'name',
type: 'string'
}, {
name: 'phone',
type: 'string'
}, {
name: 'email',
type: 'string'
}, {
name: 'birthday',
type: 'date',
dateFormat: 'm/d/Y'
}]);
If I only update the name of any contact in the datagrid, the app will only send the contact id and contact name back to server. In another words, the app will only send the updated data to the server + id (in update cases) and only the contact id in delete cases. Try to change it to true and enable Firebug plugin in your browser to see what happens. Now you need to setup a proxy like this one:
var proxy = new Ext.data.HttpProxy({
api: {
read : 'contact/view.action',
create : 'contact/create.action',
update: 'contact/update.action',
destroy: 'contact/delete.action'
}
});
FYI, this is how my reader looks like:
var reader = new Ext.data.JsonReader({
totalProperty: 'total',
successProperty: 'success',
idProperty: 'id',
root: 'data',
messageProperty: 'message' // <-- New "messageProperty" meta-data
},
Contact);
The Writer and the proxy (and the reader) can be hooked to the store like this:
// Typical Store collecting the Proxy, Reader and Writer together.
var store = new Ext.data.Store({
id: 'user',
proxy: proxy,
reader: reader,
writer: writer, // <-- plug a DataWriter into the store just as you would a Reader
autoSave: false // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
});
Where autosave identifies if you want the data in automatically saving mode (you do not need a save button, the app will send the actions automatically to the server). In this case, I implemented a save button, so every record with new or updated value will have a red mark on the cell left up corner). When the user alters a value in the grid, then a “save” event occurs (if autosave is true). Upon the “save” event the grid determines which cells has been altered. When we have an altered cell, then the corresponding record is sent to the server with the ‘root’ from the reader around it. E.g if we read with root “data”, then we send back with root “data”. We can have several records being sent at once. When updating to the server (e.g multiple edits). And to make you life even easier, let’s use the RowEditor plugin, so you can easily edit or add new records. All you have to do is to add the css and js files in your page:
<!-- Row Editor plugin css --> <link rel="stylesheet" type="text/css" href="/extjs-crud-grid/ext-3.1.1/examples/ux/css/rowEditorCustom.css" /> <link rel="stylesheet" type="text/css" href="/extjs-crud-grid/ext-3.1.1/examples/shared/examples.css" /> <link rel="stylesheet" type="text/css" href="/extjs-crud-grid/ext-3.1.1/examples/ux/css/RowEditor.css" /> <!-- Row Editor plugin js --> <script src="/extjs-crud-grid/ext-3.1.1/examples/ux/RowEditor.js"></script>
Add the plugin on you grid declaration:
var editor = new Ext.ux.grid.RowEditor({
saveText: 'Update'
});
// create grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: "NAME",
width: 170,
sortable: true,
dataIndex: 'name',
editor: {
xtype: 'textfield',
allowBlank: false
}},
{header: "PHONE #",
width: 150,
sortable: true,
dataIndex: 'phone',
editor: {
xtype: 'textfield',
allowBlank: false
}},
{header: "EMAIL",
width: 150,
sortable: true,
dataIndex: 'email',
editor: {
xtype: 'textfield',
allowBlank: false
}},
{header: "BIRTHDAY",
width: 100,
sortable: true,
dataIndex: 'birthday',
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
editor: new Ext.form.DateField ({
allowBlank: false,
format: 'm/d/Y',
maxValue: (new Date())
})}
],
plugins: [editor],
title: 'My Contacts',
height: 300,
width:610,
frame:true,
tbar: [{
iconCls: 'icon-user-add',
text: 'Add Contact',
handler: function(){
var e = new Contact({
name: 'New Guy',
phone: '(000) 000-0000',
email: 'new@loianetest.com',
birthday: '01/01/2000'
});
editor.stopEditing();
store.insert(0, e);
grid.getView().refresh();
grid.getSelectionModel().selectRow(0);
editor.startEditing(0);
}
},{
iconCls: 'icon-user-delete',
text: 'Remove Contact',
handler: function(){
editor.stopEditing();
var s = grid.getSelectionModel().getSelections();
for(var i = 0, r; r = s[i]; i++){
store.remove(r);
}
}
},{
iconCls: 'icon-user-save',
text: 'Save All Modifications',
handler: function(){
store.save();
}
}]
});
Finally, you need some server side code. This is how my Controller looks like:
package com.loiane.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.loiane.model.Contact;
import com.loiane.service.ContactService;
public class ContactController extends MultiActionController {
private ContactService contactService;
public ModelAndView view(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try{
List<Contact> contacts = contactService.getContactList();
return getModelMap(contacts);
} catch (Exception e) {
return getModelMapError("Error trying to retrieve contacts.");
}
}
public ModelAndView create(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try{
Object data = request.getParameter("data");
List<Contact> contacts = contactService.create(data);
return getModelMap(contacts);
} catch (Exception e) {
return getModelMapError("Error trying to create contact.");
}
}
public ModelAndView update(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try{
Object data = request.getParameter("data");
List<Contact> contacts = contactService.update(data);
return getModelMap(contacts);
} catch (Exception e) {
return getModelMapError("Error trying to update contact.");
}
}
public ModelAndView delete(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try{
String data = request.getParameter("data");
contactService.delete(data);
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("success", true);
return new ModelAndView("jsonView", modelMap);
} catch (Exception e) {
return getModelMapError("Error trying to delete contact.");
}
}
/**
* Generates modelMap to return in the modelAndView
* @param contacts
* @return
*/
private ModelAndView getModelMap(List<Contact> contacts){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("total", contacts.size());
modelMap.put("data", contacts);
modelMap.put("success", true);
return new ModelAndView("jsonView", modelMap);
}
/**
* Generates modelMap to return in the modelAndView in case
* of exception
* @param msg message
* @return
*/
private ModelAndView getModelMapError(String msg){
Map<String,Object> modelMap = new HashMap<String,Object>(2);
modelMap.put("message", msg);
modelMap.put("success", false);
return new ModelAndView("jsonView",modelMap);
}
/**
* Spring use - DI
* @param dadoService
*/
public void setContactService(ContactService contactService) {
this.contactService = contactService;
}
}
If you want to see all the code (complete project will all the necessary files to run this app), download it from my GitHub repository: http://github.com/loiane/extjs-crud-grid
I just want to make one more observation: You can also use dataWriter to save the data dragged from an excel file and dropped into the grid (remember DataDrop plugin?). I also included this plugin in this code project (check out my Github repository).
Happy coding!
Updated: I posted a new CRUD DataGrid example, using Spring MVC 3 and Hibernate 3.5: http://loianegroner.com/2010/09/extjs-spring-mvc-3-and-hibernate-3-5-crud-datagrid-example/



