Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ext JS 4 CRUD example

DZone's Guide to

Ext JS 4 CRUD example

· Mobile Zone ·
Free Resource

While writing my Spring-Hibernate Integration post I realize that we (as java developers) have so many frameworks available which can make life easy by rapidly developing so many common things using frameworks. This ease of development is not available in java particularly when you considering UI development, we still have to struggle with old, bad looking jsp with combination of css, jquery.

Thank god we now have so many javascript toolkits, framework that make developers' lives easy by offering so many ready-to-use widgets. ExtJS is the most advanced among those client side UI frameworks.

Today I am going to demonstrate to you how you can leverage ExtJS 4 to create CRUD application. In the next post I will try to use the same JS code with Spring MVC as a backend .

Create a HTML page which include ExtJS library and aur books.js file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>ExtJS CRUD App</title>
  <link rel="stylesheet" type="text/css" 
    href="http://cdn.sencha.com/ext/gpl/4.2.0/resources/css/ext-all.css">
  <script type="text/javascript" 
    src="http://cdn.sencha.com/ext/gpl/4.2.0/ext-all.js"></script>
  <style>
  .book-add { background-image:url('images/book_add.png');}
  div#output {margin:100px;}
  </style>
  <script type="text/javascript" src="books.js"></script>
</head>
<body>
  <div id="output"></div>
</body>
</html>

Here is the ExtJS CRUD code, I have combined it in a single file. You can follow the ExtJS 4 MVC folder structure.

Ext.onReady(function () {
  Ext.define('TechZoo.model.Book', {
    extend: 'Ext.data.Model',
    fields: [
      {name: 'title', type: 'string'},
      {name: 'author',  type: 'string'},
      {name: 'price', type: 'int'},
      {name: 'qty',  type: 'int'}
    ]
  });

  Ext.define('TechZoo.store.Books', {
    extend  : 'Ext.data.Store',
    model   : 'TechZoo.model.Book',
    fields  : ['title', 'author','price', 'qty'],
    data    : [
      { title: 'JDBC, Servlet and JSP', 
        author: 'Santosh Kumar', price: 300, qty : 12000 },
      { title: 'Head First Java', 
        author: 'Kathy Sierra', price: 550, qty : 2500 },
      { title: 'Java SCJP Certification', 
        author: 'Khalid Mughal', price: 650, qty : 5500 },
      { title: 'Spring and Hinernate', 
        author: 'Santosh Kumar', price: 350, qty : 2500 },
      { title: 'Mastering C++', 
        author: 'K. R. Venugopal', price: 400, qty : 1200 }
    ]
  });

  Ext.define('TechZoo.view.BooksList', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.bookslist',
    title: 'Books List - (ExtJS 4 CRUD example - @ Tousif Khan)',
    store: 'Books',
    initComponent: function () {
      this.tbar = [{
        text    : 'Add Book',
        action  : 'add',
        iconCls : 'book-add'
      }];
      this.columns = [
        { header: 'Title', dataIndex: 'title', flex: 1 },
        { header: 'Author', dataIndex: 'author' },
        { header: 'Price', dataIndex: 'price' , width: 60 },
        { header: 'Quantity', dataIndex: 'qty', width: 80 },
        { header: 'Action', width: 50,
          renderer: function (v, m, r) {
            var id = Ext.id();
            var max = 15;
            Ext.defer(function () {
              Ext.widget('image', {
                renderTo: id,
                name: 'delete',
                src : 'images/book_delete.png',
                listeners : {
                  afterrender: function (me) { 
                    me.getEl().on('click', function() {
                      var grid = Ext.ComponentQuery.query('bookslist')[0];
                      if (grid) {
                        var sm = grid.getSelectionModel();
                        var rs = sm.getSelection();
                        if (!rs.length) {
                          Ext.Msg.alert('Info', 'No Book Selected');
                          return;
                        }
                        Ext.Msg.confirm('Remove Book', 
                          'Are you sure you want to delete?', 
                          function (button) {
                            if (button == 'yes') {
                              grid.store.remove(rs[0]);
                            }
                        });
                      }
                    });
                  }
                }
              });
            }, 50);
            return Ext.String.format('<div id="{0}"></div>', id);
          }
        }
      ];
      this.callParent(arguments);
    }
  });

    Ext.define('TechZoo.view.BooksForm', {
      extend  : 'Ext.window.Window',
      alias   : 'widget.booksform',
      title   : 'Add Book',
      width   : 350,
      layout  : 'fit',
      resizable: false,
      closeAction: 'hide',
      modal   : true,
      config  : {
        recordIndex : 0,
        action : ''
      },
      items   : [{
        xtype : 'form',
        layout: 'anchor',
        bodyStyle: {
          background: 'none',
          padding: '10px',
          border: '0'
        },
        defaults: {
          xtype : 'textfield',
          anchor: '100%'
        },
        items : [{
          name  : 'title',
          fieldLabel: 'Book Title'
        },{
          name: 'author',
          fieldLabel: 'Author Name'
        },{
          name: 'price',
          fieldLabel: 'Price'
        },{
          name: 'qty',
          fieldLabel: 'Quantity'
        }]
      }],
      buttons: [{
        text: 'OK',
        action: 'add'
      },{
        text    : 'Reset',
        handler : function () { 
          this.up('window').down('form').getForm().reset(); 
        }
      },{
        text   : 'Cancel',
        handler: function () { 
          this.up('window').close();
        }
      }]
    });

  Ext.define('TechZoo.controller.Books', {
    extend  : 'Ext.app.Controller',
    stores  : ['Books'],
    views   : ['BooksList', 'BooksForm'],
    refs    : [{
      ref   : 'formWindow',
      xtype : 'booksform',
      selector: 'booksform',
      autoCreate: true
    }],
    init: function () {
      this.control({
        'bookslist > toolbar > button[action=add]': {
          click: this.showAddForm
        },
        'bookslist': {
          itemdblclick: this.onRowdblclick
        },
        'booksform button[action=add]': {
          click: this.doAddBook
        }
      });
    },
    onRowdblclick: function(me, record, item, index) {
      var win = this.getFormWindow();
      win.setTitle('Edit Book');
      win.setAction('edit');
      win.setRecordIndex(index);
      win.down('form').getForm().setValues(record.getData());
      win.show();
    },
    showAddForm: function () {
      var win = this.getFormWindow();
      win.setTitle('Add Book');
      win.setAction('add');
      win.down('form').getForm().reset();
      win.show();
    },
    doAddBook: function () {
      var win = this.getFormWindow();
      var store = this.getBooksStore();
      var values = win.down('form').getValues();

      var action = win.getAction();
      var book = Ext.create('TechZoo.model.Book', values);
      if(action == 'edit') {
        store.removeAt(win.getRecordIndex());
        store.insert(win.getRecordIndex(), book);  
      }
      else {
        store.add(book);
      }
      win.close();
    }
  });

  Ext.application({
    name  : 'TechZoo',
    controllers: ['Books'],
      launch: function () {
        Ext.widget('bookslist', {
          width : 500,
          height: 300,
          renderTo: 'output'
        });
      }
    }
  );
});

Output:

Open the HTML file in any browser, the Output will look similar to below. You can click to add new Book record in GRID.

Double click to any of the GRID row to edit the record.

View Live Demo



Topics:
java ,html5 ,javascript ,tips and tricks

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}