`

自己封装的Extjs组件combox

 
阅读更多

http://fjza1168.blog.163.com/blog/static/3666003620110104647573/  

原文地址:自己封装的Extjs组件combox(2    原文作者:chy2z

效果图:以摸板形式绑定数据

自己封装的Extjs组件combox(2) - chy2z - 黑暗行动


 

效果图:及联查询

自己封装的Extjs组件combox(2) - chy2z - 黑暗行动

效果图:绑定本地数据,默认选种第一个

自己封装的Extjs组件combox(2) - chy2z - 黑暗行动


 

源代码:

Ext.namespace("Ext.tet");
Ext.tet.ComboBox=new Ext.extend(Ext.form.ComboBox,{
         DataSource:{tableName:null,cols:[],relationValue:null,query:null,search:null,where:null,orderBy:null,direction:null},
         ajaxUrl:"/ExtProject/pagination/comBoxPagination.ashx",
         typeAhead:true,        
         forceSelection: true,
         triggerAction: 'all',                                   //all 不起用 autocomplete功能,  query 起用autocomplete功能
         emptyText:'请选择信息',
         selectOnFocus:true,
         anchor:"97%",         
         blankText:'请选择一个',
         readOnly:true,
         minChars:1,
         lazyRender:true,
         selectFirstRow:false,                                   //默认不选种第一项
         lazyInit:true,
         initComboBox:function(){
              if(this.DataSource){   
                 if(Ext.type(this.DataSource)=="object"){        //服务器
                       this.mode="remote";
                       if(this.pageSize){                        //分页,回掉数据
                                 triggerAction="query";                            
                       }                      
                 } 
                 else if(Ext.type(this.DataSource)=="array"){    //本地数据
                       this.mode="local";
                 }
              }
              else Ext.Msg.alert("提示","DataSource为空");
         },
         createStore:function(){             
              if(this.DataSource){     //[valueField不能有重复值]                 
                       if(!this.displayField) this.displayField=this.valueField;
                       if(!this.valueField) this.valueField=this.displayField;
                       if(this.mode=="local"){
                            this.store=new Ext.data.SimpleStore({
              fields:[this.displayField,this.valueField],
              data:this.DataSource
             });
                       }
                       else{
                             this.store=new Ext.data.Store({
                                       proxy:new Ext.data.HttpProxy(
                                       {
                                           
url:this.ajaxUrl,
                                            method:"POST"
                                       }),
                                       reader:new Ext.data.JsonReader(
                                       {
                                                    fields:this.DataSource["cols"],
                                                    root:"data",
                                                    totalProperty:"totalCount"                      
                                       }),
                                       remoteSort:true,
                                       sortInfo: {field:this.DataSource["orderBy"]||this.displayField,direction:this.DataSource["direction"]||"Desc"},
                                       listeners:{
                                          "beforeload":function(ds,option){
                                                 if(ds.baseParams["relationValue"]==null){                             //级联查询
                                                        if(ds.baseParams["query"]!=null||ds.baseParams["query"]==""){
                                                                  ds.baseParams["where"]=ds.baseParams["search"]+" like '%" + ds.baseParams["query"] + "%'";
                                                                  ds.baseParams["query"]=null;
                                                        }
                                                 }
                                                 else{  
                                                        ds.baseParams["where"]=ds.baseParams["search"]+" like '%" + ds.baseParams["relationValue"] + "%'";
                                                 } 
                                           }
                                       },
                                       baseParams:{start:0,limit:this.pageSize||1000,search:this.DataSource["search"]||this.displayField,relationValue:this.DataSource["relationValue"]||null,tableName:this.DataSource["tableName"],key:this.valueField,columns:this.DataSource["cols"].join(","),where:this.DataSource["where"]}
                               });
                               this.store.load();
                      } 
             }                  
         },
         render:function(comb){
                Ext.tet.ComboBox.superclass.render.apply(this, arguments);
                if(this.selectFirstRow){
                       this.setValue(this.getStore().getAt(0).data[this.valueField]);
                       this.fireEvent("select",this,this.getStore().getAt(0),0); 
                }                      
         },
         constructor:function(options){                              
                Ext.apply(this,options);
                this.initComboBox();
                this.createStore();                                                           
                Ext.tet.ComboBox.superclass.constructor.call(this);
         }
});

Ext.reg('combobox',Ext.tet.ComboBox);


 

调用方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
<link rel="stylesheet" type="text/css" href="../../Client/Ext/resources/css/ext-all.css" />
<script type="text/javascript" src="../../Client/Ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../Client/Ext/ext-all.js"></script>
<script type="text/javascript" src="../class/ComboBox.js"></script>
</head>
<script language=javascript>
Ext.BLANK_IMAGE_URL="../../Client/Images/s.gif";   
window.onload=function(){
                    new Ext.Panel({
                                title:"本地",
                                frame:true,
                                width:375,
                       height:140,
                       plain:true,
                       layout:"form",
                       defaultType:"textfield",
                       labelWidth:60,
                       defaults:{anchor:"95%",msgTarget:"side"},
                       buttonAlign:"center",
                       bodyStyle:"padding:0 0 0 0",
                                renderTo:"panel1",
                                items:[                              
                              {
                                            xtype:"combobox",
                                            fieldLabel:"性别",
                                            valueField:"value",
                                            DataSource:[["男"],["女"]],
                                            selectFirstRow:true
                              },
                              new Ext.tet.ComboBox({
                                            fieldLabel:"性别",
                                            valueField:"value",
                                            DataSource:[["男"],["女"]]
                              }),
                              new Ext.tet.ComboBox({
                                            id:"testcomb",
                                            readOnly:false,
                                            fieldLabel:"工资级别",
                                            displayField:"text",
                                            valueField:"value",
                                            DataSource:[["工程师","10000"],["项目经理","6000"],["程序员","4000"]], 
                                            selectFirstRow:true,                                          
                                            listeners:{
                                                        "select":function(combo,rec,index)
                                                        {
                                                                  alert(combo.getValue());
                                                        }
                                                     }
                              })
                                ]    
                    });
                   
                    //Ext.getCmp("testcomb").setValue(Ext.getCmp("testcomb").getStore().getAt(0).data.value);
                   
                    //alert(Ext.getCmp("testcomb").getValue());
                   
                    //alert(Ext.getCmp("testcomb").valueField);
                   
                    new Ext.Panel({
                                title:"服务器",
                                frame:true,
                                width:375,
                       height:200,
                       plain:true,
                       layout:"form",
                       defaultType:"textfield",
                       labelWidth:60,
                       defaults:{anchor:"95%",msgTarget:"side"},
                       buttonAlign:"center",
                       bodyStyle:"padding:0 0 0 0",
                                renderTo:"panel2",
                                items:[

                              new Ext.tet.ComboBox({ 
                                            tpl: '<tpl for="."><div ext:qtip="{BorrowNo}" class="x-combo-list-item">姓名:{LoginName},编号:{BorrowNo}</div></tpl>',
                                            readOnly:false,                                          
                                            fieldLabel:"图书编号",
                                            displayField:"BorrowNo",  
                                            DataSource:{tableName:"Borrow_View",cols:["BorrowNo","LoginName"]},
                                            listeners:{
                                                        "select":function(combo,rec,index)
                                                        {
                                                                  alert(combo.getValue());
                                                        }
                                                     }
                              }),
                              new Ext.tet.ComboBox({ 
                                            tpl: '<tpl for="."><div ext:qtip="{Name}" class="x-combo-list-item">姓名:{Name},登陆名:{LoginName}<br/>身份证:{IdentityCard}</div></tpl>',
                                            readOnly:false,                                          
                                            fieldLabel:"用户姓名",
                                            displayField:"Name", 
                                            valueField:"LoginName", 
                                            pageSize:10, 
                                            resizable:true,
                                            DataSource:{tableName:"Users",cols:["Name","LoginName"]},
                                            listeners:{
                                                        "select":function(combo,rec,index)
                                                        {
                                                                  alert(combo.getValue());
                                                        }
                                                     }
                             })     
                                ]    
                    });
                   
                                              
                    new Ext.Panel({
                                title:"及联查询",
                                frame:true,
                                width:375,
                       height:200,
                       plain:true,
                       layout:"form",
                       defaultType:"textfield",
                       labelWidth:70,
                       defaults:{anchor:"95%",msgTarget:"side"},
                       buttonAlign:"center",
                       bodyStyle:"padding:0 0 0 0",
                                renderTo:"panel3",
                                items:[
                                        {
                                          xtype:"combobox",
                                          fieldLabel:"身份证(1)",
                                          valueField:"value",
                                          DataSource:[["0238"],["0236"],["0237"]],
                                          selectFirstRow:true,
                                          listeners:{
                                                "select":function(combo,rec,index)
                                                {                                                       
                                                      Ext.getCmp("user").reset();
                                                      Ext.getCmp("user").lastQuery=combo.getValue();                       //清除上一次查询 
                                                      Ext.getCmp("user").getStore().baseParams["search"]="IdentityCard";   //查询字段
                                                      Ext.getCmp("user").getStore().baseParams["relationValue"]=combo.getValue();//查询值
                                                }
                                             }
                              },
                              new Ext.tet.ComboBox({ 
                                          id:"user",
                                          tpl: '<tpl for="."><div ext:qtip="{Name}" class="x-combo-list-item">姓名:{Name},登陆名:{LoginName}<br/>身份证:{IdentityCard}</div></tpl>',
                                          readOnly:true,                                          
                                          fieldLabel:"用户姓名(2)",
                                          displayField:"Name", 
                                          valueField:"LoginName", 
                                          pageSize:10, 
                                          resizable:true,
                                          DataSource:{tableName:"Users",cols:["Name","LoginName","IdentityCard"]},                                         
                                          listeners:{
                                                "select":function(combo,rec,index)
                                                {
                                                          alert(combo.getValue());
                                                }
                                             }
                              })
                                ]
                          });
}
</script>
<body>
<div>
<div id="panel1"></div>
<div id="panel2"></div>
<div id="panel3"></div>
</div>
</body>
</html>


 

comBoxPagination.ashx 代码:

<%@ WebHandler Language="C#" Class="comBoxPagination" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class comBoxPagination : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string tableName = context.Request.Form["tableName"];
        string key = context.Request.Form["key"];
        string starts = context.Request.Form["start"];
        string limits = context.Request.Form["limit"];
        string sort = context.Request.Form["sort"];
        string dir = context.Request.Form["dir"];
        string where = context.Request.Form["where"];
        string columns = context.Request.Form["columns"];
        string JSON = "";
        if (starts != null && limits != null)
        {
            int start = int.Parse(starts);
            int limit = int.Parse(limits);
            if (where != null)
                if (where == "null" || where.Trim() == "") where = null;
            JSON = GetPaginationJson(tableName, key, start, limit, sort, dir, where, columns);
        }
        else
        {
            context.Response.Write("{success:'false'}");
        }

        context.Response.Write(JSON);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public string GetPaginationJson(string tableName, string key, int start, int limit, string sort, string dir, string where, string columns)
    {
        JSONHelper json = new JSONHelper();
        json.success = true;
        DataSet ds = GetInfo(tableName, key, start, limit, sort, dir, where, columns);
        string[] fields = columns.Split(',');
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            foreach (string col in fields)
            {
                json.AddItem(col, dr[col].ToString());
            }
            json.ItemOk();
        }
        json.totlalCount = GetInfoCount(tableName, where);
        return json.ToString();
    }

    /// <summary>
    /// 得到总记录数
    /// </summary>
    /// <returns></returns>
    public int GetInfoCount(string tableName, string where)
    {
        string sql = "";
        if (where == null)
            sql = "select count(*) from " + tableName;

        else
            sql = "select count(*) from " + tableName + " where " + where;
        return int.Parse(CHY.DbHelperSQL.ExecuteScalar(sql).ToString());
    }

    public DataSet GetInfo(string tableName, string key, int start, int limit, string sort, string dir, string where, string columns)
    {
        string sql;
        if (sort == null)
            sort = key;
        if (dir == null)
            dir = "DESC";
        if (columns == null)
            columns = "*";
        if (where == null)
            sql = "select distinct top " + limit + " " + columns + " from " + tableName + " where " + key + " not in(select top " + start + " " + key + " from " + tableName + " order by " + sort + " " + dir + ") order by " + sort + " " + dir;
        else
            sql = "select distinct top " + limit + " " + columns + " from " + tableName + " where " + where + " and " + key + " not in(select top " + start + " " + key + " from " + tableName + " where " + where + " order by " + sort + " " + dir + ") order by " + sort + " " + dir;

        return CHY.DbHelperSQL.Query(sql);
    }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics