Ext js 应用系列一:EditGrid

来源:互联网 发布:md5是哈希算法吗 编辑:程序博客网 时间:2024/06/05 08:36
最近在notes应用中使用Ext js,对于一些被用到的实例,记录下来,以备查阅。我用的Ext  版本比较老,是1.0.1的,艾,现在都2.0了没想到,升级那么快,有机会咱也与时俱进一把。
在notes中应用Ext js,我的做法是,将js lib文件,样式文件和图片资源文件,引入到share resource 的file resource下。然后在相应的表单,页面等设计元素中引用。
Ext js中的EditGrid,主要被我用作表单中的行项目,因为,这种设计可以减少对一个表单的应用(:(,不过花费的时间还真不少);实现该功能,主要应用到的设计元素有,表单,视图和代理。
1、表单,主要用于显示EditGrid,主要html代码:
<table id=layout border=0 cellpadding=0 cellspacing=0 width=100%><tr><td>
<div id="grid-panel" style="width:90%;height:200px;">
<div id="editor-grid"></div>
<div id="editGrid"></div>
</div>
</td></tr></table>

2、用于生成EditGrid的js
/*
 * Ext JS Library 1.0.1
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://www.extjs.com/license
 
*/


Ext.onReady(
function(){
    
var thisform = document.forms[0];
    
var key = thisform.mLineItemKey.value;
    
var isEdit = getEditModel();
    
    
function getEditModel(){
        
var search = window.location.search.toLowerCase();
        
if(search.indexOf("opendocument")>0)
            
return "false";
        
else
            
return "true";
    }

    
    
function doDelete(isOK){
        
if(isOK=="yes")   
        
{       
                 
var m = grid.getSelections();     
                 
var jsonData = '[' + Ext.util.JSON.encode(m[0].data);   
                 
for(i=1;i<m.length;i++)
                 
{   
                 jsonData 
= jsonData + ',' + Ext.util.JSON.encode(m[i].data);                 
                 }
   
                 jsonData 
= jsonData + ']' ;    
                 
            
var con = new Ext.data.Connection();
            con.request(
{
                url: dbpath
+'wxServerProduct?openAgent&action=delete&rdm'+getRandom(),
                params: 
{data:jsonData},
                callback: 
function (opts, success, response){
                    
if(success) {
                        
var returnValue = getXmlNodeValue(response.responseXML,"response");
                        
if(returnValue.toLowerCase()!="success")
                            alert(returnValue);
                        
else{
                            alert(
'Records delete Successfully!');
                            ds.reload();                
                        }

                    }

                }

            }
)     
         }
   
         
else  
         
{    
             grid.getSelectionModel().clearSelections();            
        }
          
    }

    
//Delete grid data to domino
    function onDeleteClick(){
         
var m = grid.getSelections();   
         
if(m.length > 0)   
         
{   
             Ext.MessageBox.confirm(
'Message''Are sure to delete?' , doDelete);      
         }
   
         
else  
         
{   
             Ext.MessageBox.alert(
'Message''Please select your records!');   
         }
   
    }

    
//Save grid data to Domino     
    function doSave(isOK){
        
if(isOK=="yes"){
            
var jsonData = "[";
            
for(i=0;i<ds.getCount();i++{
                   record 
= ds.getAt(i);
                   jsonData 
+= Ext.util.JSON.encode(record.data) + ",";
               }
             
            jsonData 
= jsonData.substring(0,jsonData.length-1+ "]"
            
var con = new Ext.data.Connection();
            
            con.request(
{
                url: dbpath
+'wxServerProduct?openAgent&action=update&rdm'+getRandom(),
                params: 
{data:jsonData},
                callback: 
function (opts, success, response){
                    
if(success) {
                        
var returnValue = getXmlNodeValue(response.responseXML,"response");
                        
if(returnValue.toLowerCase()!="success")
                            alert(returnValue);
                        
else{
                            alert(
'Records Save Successfully!');
                            ds.reload();                    
                        }

                    }

                }

            }
)
        }

    }


    
function onSaveClick(){
         
var m = ds.modified.slice(0);   
         
if(m.length > 0)   
         
{   
             Ext.MessageBox.confirm(
'Message''Are your sure to save?' , doSave);      
         }
   
         
else  
         
{   
             Ext.MessageBox.alert(
'Message''Sorry, you have not done any modification!');   
         }
          
    }

    
    
// shorthand alias
    var fm = Ext.form, Ed = Ext.grid.GridEditor;
    
// the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cm = new Ext.grid.ColumnModel([{
           header: 
"UNID",
           dataIndex: 
'unid',
           width: 
50,
           hidden: 
true
        }
,{
           header: 
"Product",
           dataIndex: 
'product',
           width: 
220,
           editor: 
new Ed(new fm.TextField({
               allowBlank: 
true
           }
))
        }
,{
           header: 
"Quantity",
           dataIndex: 
'quantity',
           width: 
80,
           editor: 
new Ed(new fm.NumberField({
               allowBlank: 
false,
               allowNegative: 
false,
               maxValue: 
10
           }
))
        }
,{
           header: 
"Total Price",
           dataIndex: 
'totalPrice',
           width: 
80,
           align: 
'right',
           renderer: 
'usMoney',
           editor: 
new Ed(new fm.NumberField({
               allowBlank: 
false,
               allowNegative: 
false,
               maxValue: 
10
           }
))
        }
,{
           header: 
"Vendor",
           dataIndex: 
'vendor',
           width: 
150,
           editor: 
new Ed(new fm.TextField({
               allowBlank: 
true
           }
))
        }
,{
           header: 
"Purpose",
           dataIndex: 
'purpose',
           width: 
200,
           editor: 
new Ed(new fm.TextField({
               allowBlank: 
true
           }
))
        }
]);

    
// by default columns are sortable
    cm.defaultSortable = true;

    
// this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Row = Ext.data.Record.create([
           
// the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'key'},
           
{name: 'unid'},
           
{name: 'product'},
           
{name: 'quantity'},
           
{name: 'totalPrice'},
           
{name: 'vendor'},
         
{name: 'purpose'}
      ]);

    
// create the Data Store

    
var gridOptions = {
        
// load using HTTP
        //proxy: new Ext.data.HttpProxy({url: dbpath+'wLineItemServerProduct?openView&RestrictToCategory='+key+"&rdm="+getRandom()}),
        
       proxy: 
new Ext.data.HttpProxy({url: dbpath+"wxServerProduct?openAgent&action=display&view=wLineItemServerProduct&category="+key+"&rdm="+getRandom()}),
        
        
// the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               
// records will have a "plant" tag
               record: 'row'
           }
, Row)
    }

    
var ds = new Ext.data.Store(gridOptions);
    
// create the editor grid or a normal grid
    if(isEdit=="true"){
        
var grid = new Ext.grid.EditorGrid('editor-grid'{
            ds: ds,
            cm: cm,
            selModel: 
new Ext.grid.RowSelectionModel(),
            enableColLock: 
false
        }
);
    }
else{
        
var grid = new Ext.grid.Grid('editor-grid'{
            ds: ds,
            cm: cm
        }
);
    }

    
var layout = Ext.BorderLayout.create({
        center: 
{
            margins:
{left:3,top:3,right:3,bottom:3},
            panels: [
new Ext.GridPanel(grid)]
        }

    }
'grid-panel');

    
// render it
    grid.render();

    
    
var gridHead = grid.getView().getHeaderPanel(true);
    
    
//control the actions to the grid
    var tbOptions = [{}];
    
if(isEdit=="true"){
        tbOptions 
= [{
            text: 
' Add ',
            handler : 
function(){
                
var r = new Row({
                 key: thisform.mLineItemKey.value,
                 unid: 
'',
                    product: 
'',
                    quantity: 
0,
                    totalPrice: 
0,
                    vendor: 
'',
                    purpose: 
''
                }
);
                grid.stopEditing();
                ds.insert(
0, r);
                grid.startEditing(
00);
            }

        }
,{
            text: 
' Save ',
            handler :
function(){
               onSaveClick(); 
          }

        }
,{
            text: 
' Delete ',
            handler : 
function(){
            onDeleteClick();
            }

        }
];

    }


    
var tb = new Ext.Toolbar(gridHead,tbOptions);

    
// trigger the data store load
    ds.load();
}
);

3、用于显示xml文档的视图,xml文件可以用表单+嵌入视图的模式生成,也可以用LS+视图的方式print出来,我采用了后者,原因是我的Ext js版本比较老, 其中的HttpProxy采用Get方式上传数据,而非Post方式,导致xml文件有缓存,dataStore的reload方法总是不会更新Grid。因此,只能在服务器端print xml ,强行设置Cache-Control:No-Cache。
视图中显示xml可以如下:
"<row>"
+ "<key>" + @Text(key) + "</key>"
+ "<unid>" + @Text(@DocumentUniqueID) + "</unid>"
+ "<product>" + @Text(product)+ "</product>"
+ "<quantity>" + @Text(quantity)+ "</quantity>"
+ "<totalPrice>" + @Text(totalPrice) + "</totalPrice>"
+ "<vendor>" + @Text(vendor) + "</vendor>"
+ "<purpose>" + @Text(purpose) + "</purpose>"
+ "</row>" + @NewLine

4、服务器端运行的LS
LS主要用于执行一些操作,如save,delete等,为了专门处理Ext 的ajax操作,我写了一个AjaxRequest的class以便于处理不同的ajax操作请求,EditGrid中主要用到的方法有:

    
Public Function deleteJsonToNote(db As NotesDatabase,jObjs As Variant) As String
        
        
On Error Goto errHandle
        
If db Is Nothing Then
            deleteJsonToNote 
= "Error, database is null"
            
Exit Function
        
End If
        
        
If Not Isarray(jObjs) Then
            deleteJsonToNote 
= "Error, JSON is null"
            
Exit Function
        
End If
        
        Forall obj 
In jObjs
            
Dim doc As NotesDocument
            
Dim unid As String
            unid 
= obj.GetItem("unid")
            
If unid="" Then
                
Set doc = Nothing
            
Else
                
Set doc = db.GetDocumentByUNID(unid)
            
End If
            
            
If Not doc Is Nothing Then
                
Call doc.Remove(True)
            
End If
            
        
End Forall
        
        
Exit Function
errHandle:
        deleteJsonToNote 
= "Error:"+Cstr(Err)+","+Error$         
    
End Function


    
Public Function updateJsonToNote(db As NotesDatabase, formname As String, jObjs As Variant) As String
        
        
On Error Goto errHandle
        
If db Is Nothing Then
            updateJsonToNote 
= "Error, database is null"
            
Exit Function
        
End If
        
        
If formname="" Or formname=Null Then
            updateJsonToNote 
= "Error, form name is null"
            
Exit Function
        
End If
        
        
If Not Isarray(jObjs) Then
            updateJsonToNote 
= "Error, JSON is null"
            
Exit Function
        
End If
        
        Forall obj 
In jObjs
            
Dim docTemp As NotesDocument
            
Dim doc As NotesDocument
            
Dim unid As String
            unid 
= obj.GetItem("unid")
            
If unid="" Then
                
Set doc = Nothing
            
Else
                
Set doc = db.GetDocumentByUNID(unid)
            
End If
            
            
If Not doc Is Nothing Then
                
Call doc.Remove(True)
            
End If
            
Set docTemp = db.CreateDocument()
            docTemp.form 
= formname
            Forall v 
In obj.ItemList
                
Call docTemp.ReplaceItemValue(Listtag(v),v)
            
End Forall
            
Call docTemp.Save(True,False)
        
End Forall
        
        
Exit Function
errHandle:
        updateJsonToNote 
= "Error:"+Cstr(Err)+","+Error$         
    
End Function

还有一点很幸运,有前辈已经写了一个LS的JSONclass,download and 应用之,爽!!!!!
'********************************* JSON **************************************************
'*** @Usage: The public interface allows you to create JSON using Stringify and
'*** process JSON using the Parse method.
'*** @Version: 1.0.0
'*** @Author: Alan Faubel
'*******************************************************************************************
原创粉丝点击