Extjs ComboBox 확장

15206 단어 combobox
역할:
프로그램에서는 다른 곳의 매개 변수를 가져와 이 ComboBox에 매개 변수를 가지고 결과를 조회하고 결과의 일부 필드 값을 필요한 곳(다른 곳)으로 설정하는 경우가 종종 있다.
[Grid에서도 지원] 관련 매개 변수를 설정하지 않으면 일반 ComboBox입니다!
 
 
Ext.ns("dnet.base");
dnet.base.AbstractCombo = Ext.extend(Ext.form.ComboBox, {

	 _dataProviderFields_  :null   //       record($Model)
	,_dataProviderName_ : null     //    
	,fieldMapping : null        //     Field 
	,paramMapping: null    // ex: paramMapping: [{lovField:"...lovFieldName", dsField: "...dsFieldName"} ]
    ,callFromGrid:null     //  Combo Grid      (required if this combox in grid)
    ,storeUrl:null
    ,minChars:0
    ,listEmptyText:"Can't find fit data !"
	/**   Store**/
	,_createStore_: function() {

		this.store = new Ext.data.Store({
	        remoteSort:true
	       ,reader: new Ext.data.JsonReader(
	   		 	{totalProperty: 'totalCount',idProperty: 'id',root: 'data',messageProperty: 'message'}
				,Ext.data.Record.create(this._dataProviderFields_)
			)
	       ,listeners: { "exception":{ fn:  this.proxyException, scope:this }}
	       ,url:this.storeUrl
		})
	    this.store.proxy.getConnection().async = false;//  
	}
    /**        doQuery  ,   !**/
	/*       doQuery()  
	 initQuery : function(){
        this.doQuery(this.getRawValue());
     },
	*/
    ,doQuery : function(q, forceAll){
        q = Ext.isEmpty(q) ? '' : q;
        var qe = {
            query: q,
            forceAll: forceAll,
            combo: this,
            cancel:false
        };

        if(this.fireEvent('beforequery', qe)===false || qe.cancel){
            return false;
        }
        q = qe.query;
        forceAll = qe.forceAll;
        if(forceAll === true || (q.length >= this.minChars)){
            if( (this.lastQuery !== q) || (this.paramMapping != null && this.paramMapping.length>0) ){
                this.lastQuery = q;
                if(this.mode == 'local'){
                    this.selectedIndex = -1;
                    if(forceAll){
                        this.store.clearFilter();
                    }else{
                        this.store.filter(this.displayField, q);
                    }
                    this.onLoad();
                }else{
                    //this.store.baseParams[this.queryParam] = q;//      code
                    var bp = {}
                    bp[this.queryParam]=q;
					if (this.paramMapping != null) {
					   this._mapFilterFields_(bp);
					}
					/**                   ,
					 *       this.store.baseParams["data"]=Ext.encode(bp)
					 *   data          .
					 */
                    this.iteratorSetbaseParam(bp);                   
                    this.store.load({
                        params: this.getParams(q)
                    });
                    this.expand();
                }
            }else{
                this.selectedIndex = -1;
                this.onLoad();
            }
        }
    }
    ,iteratorSetbaseParam:function(bp){
    	this.store.baseParams[this.queryParam]=bp[this.queryParam];
    	if(this.paramMapping !=null){
    	   for(var i=0;i<this.paramMapping.length;i++){
    	      this.store.baseParams[this.paramMapping[i].param]=bp[this.paramMapping[i].param];
    	   }
    	}
    }
    /**        pagesize  , store         ! **/
    ,getParams : function(q){
//        var p = {};
//        //p[this.queryParam] = q;
//        if(this.pageSize){
//            p.start = 0;
//            p.limit = this.pageSize;
//        }
//        return p;
        var params = {},
            paramNames = this.store.paramNames;
        if(this.pageSize){
            params[paramNames.start] = 0;
            params[paramNames.limit] = this.pageSize;
        }
        return params;
    }
    /**        assertValue()  !**/
	,assertValue  : function(){
        var val = this.getRawValue(),
            rec = this.findRecord(this.displayField, val);
        if(!rec && this.forceSelection){
			this.setRawValue("");
			if(val.length > 0 && val != this.emptyText){
				//this.el.dom.value = Ext.value(this.lastSelectionText, '');
                this.applyEmptyText();
            }else{
                this.clearValue();
            }

            this._mapReturnFields_(null);

        }else{
            if(rec){
                // onSelect may have already set the value and by doing so
                // set the display field properly.  Let's not wipe out the
                // valueField here by just sending the displayField.
                this._mapReturnFields_(rec);
                if (val == rec.get(this.displayField) && this.value == rec.get(this.valueField)){

				    return;
                }
                val = rec.get(this.valueField || this.displayField);
            } else {
            	if (val != this.value ) {
            		this._mapReturnFields_(null);
            	}			   
			}
			if (this.getValue() != val) {
               this.setValue(val);
			}

        }
    }
    /** onSelect           ! **/
    ,onSelect : function(record, index){
        if(this.fireEvent('beforeselect', this, record, index) !== false){
            this.setValue(record.data[this.valueField || this.displayField]);
            if(this.fieldMapping!=null){
            	this._mapReturnFields_(record);// select       ,              (add after)
            }
            this.collapse();

            this.fireEvent('select', this, record, index);
        }
    }
    /** Return  **/
    ,_mapReturnFields_: function(crec) {   // crec combo selected record[Selected Record]
    	if(!Ext.isEmpty(this.callFromGrid)){
    		//           SelectionModel     ,           
    		 var mrec=this.callFromGrid.getSelectionModel().getSelected();//          (      )
       		 this._mapReturnFieldsExecute_(crec,mrec);//crec combo     ,mrec combo  Grid    ,  combo       Grid 
    	}else{
    		 this._mapReturnFieldsExecute_(crec);
    	}
    }

    ,_mapReturnFieldsExecute_: function(crec, mrec) {   // crec combo selected record
    	if(crec!=null){//                
	        if (this.fieldMapping != null) {
	           for(var i=0, len=this.fieldMapping.length; i<len; i++ ) {
		          if (!Ext.isEmpty(this.callFromGrid)) {
		            mrec.set( this.fieldMapping[i].field ,crec.get(this.fieldMapping[i].column) )  ;
		          }else {
		            Ext.getCmp(this.fieldMapping[i].field).setValue( crec.get(this.fieldMapping[i].column) );
		            Ext.getCmp(this.fieldMapping[i].field).fireEvent( "change");
		          }
			   }
			}
    	}else{//       ,         .
    	    if (this.fieldMapping != null) {
	           for(var i=0, len=this.fieldMapping.length; i<len; i++ ) {
		          if (!Ext.isEmpty(this.callFromGrid)) {
		            mrec.set( this.fieldMapping[i].field ,"")  ;
		          }else {
		            Ext.getCmp(this.fieldMapping[i].field).setValue("") ;
		            Ext.getCmp(this.fieldMapping[i].field).fireEvent( "change");
		          }
			   }
			}
    	}
	}
	/** Filter **/
    ,_mapFilterFields_: function(bp) {   // empty object which is added to store.baseParams
    	if(!Ext.isEmpty(this.callFromGrid)){//    GridPanel EditorGridPanel 
    		 //           SelectionModel     ,           
    		 var mrec=this.callFromGrid.getSelectionModel().getSelected();//          (      )
       		 this._mapFilterFieldsExecute_(bp,mrec);
    	}else{
    		 this._mapFilterFieldsExecute_(bp);
    	}
    }
    ,_mapFilterFieldsExecute_: function(bp, mrec) {   // bp:basePrams for combo query;mrec:Grid Edit Record
		var newParamVal;
    	var oldParamVal;
        if (this.paramMapping != null) {
        	for(var i=0, len=this.paramMapping.length; i<len; i++ ) {
	        	if(!Ext.isEmpty(this.callFromGrid)){//    GridPanel  EditorGridPanel 
				   	newParamVal = (!Ext.isEmpty(this.paramMapping[i].field))?mrec.get( this.paramMapping[i].field ):this.paramMapping[i].value ;
				   	//            
	        	}else{
	        	    newParamVal = (!Ext.isEmpty(this.paramMapping[i].field))?Ext.getCmp(this.paramMapping[i].field).getValue():this.paramMapping[i].value;
	        	    //    
	        	}
	        	oldParamVal = this.store.baseParams[this.paramMapping[i].param];//      baseParam      
	        	/*      ,                 ,        。
		        if (newParamVal != oldParamVal) {//              
		            bp[this.paramMapping[i].param]=newParamVal;
		        }
		        */
	        	bp[this.paramMapping[i].param]=newParamVal;
	       }
        }
    }
    /**                ,       ! **/
    ,getValue : function(){
		var v = null;
        if(this.valueField){
            v= Ext.isDefined(this.value) ? this.value : '';
        }else{
            v= Ext.form.ComboBox.superclass.getValue.call(this);
        }
        if (this.initialConfig["caseRestriction"] == "uppercase" && !Ext.isEmpty(v) )v=v.toUpperCase();
        return v;
    }
    /** proxy exception**/
    , proxyException: function(dataProxy, type, action , options , response , arg ) {
        if(type=="response") {
          this.afterAjaxFailure(response , options);
        } else {
           alert(response.message.substr(0,1500));
        }
	  }
    , afterAjaxFailure: function(response , options) {
      	this.dc____ajaxfailure(response , options);

	  }

    /** initEvent **/
	,initEvents : function(){
        Ext.form.ComboBox.superclass.initEvents.call(this);



        this.keyNav = new Ext.KeyNav(this.el, {
            "up" : function(e){
                this.inKeyMode = true;
                this.selectPrev();
            },

            "down" : function(e){
                if(!this.isExpanded()){
                    this.onTriggerClick();
                }else{
                    this.inKeyMode = true;
                    this.selectNext();
                }
            },

            "enter" : function(e){
                this.onViewClick(true);
                //if(this.isExpanded()){
                	e.stopEvent();
                	e.stopPropagation();
                	e.preventDefault();
				//}
				return false;
            },

            "esc" : function(e){
                this.collapse();
            },

            "tab" : function(e){
                if (this.forceSelection === true) {
                    this.collapse();
                } else {
                    this.onViewClick(false);
                }
                return true;
            },

            scope : this,

            doRelay : function(e, h, hname){
                if(hname == 'down' || this.scope.isExpanded()){
                    // this MUST be called before ComboBox#fireKey()
                    var relay = Ext.KeyNav.prototype.doRelay.apply(this, arguments);
                    if(!Ext.isIE && Ext.EventManager.useKeydown){
                        // call Combo#fireKey() for browsers which use keydown event (except IE)
                        this.scope.fireKey(e);
                    }
                    return relay;
                }
                return true;
            },
            forceKeyDown : true,
            defaultEventAction: 'stopEvent'
        });
        this.queryDelay = Math.max(this.queryDelay || 10,
                this.mode == 'local' ? 10 : 250);
        this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
        if(this.typeAhead){
            this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
        }
        if(!this.enableKeyEvents){
            this.mon(this.el, 'keyup', this.onKeyUp, this);
        }
    }
	,onRender : function(ct, position){
		dnet.base.AbstractCombo.superclass.onRender.call(this, ct, position);
	}
	
	,dc____ajaxfailure:function(response , options) {
		Ext.MessageBox.hide();

      	var msg = response.responseText;
		if (msg && msg.length > 2000) { msg = msg.substr(0,2000);}
      	Ext.Msg.show({
	        //  title: 'HTTP:'+response.status+' '+ response.statusText
	          msg: msg
	         ,buttons: {ok:'OK'} //, cancel:'Details'
	         ,scope:this
	         ,icon: Ext.MessageBox.ERROR
	         ,_detailedMessage_:response.responseText

	      });
	}
});
Ext.reg('xcombo', dnet.base.AbstractCombo);

    
 
 
 
다음은 사용 예입니다.
이러한 상황은 Grid에서 사용되는 상황입니다. 즉, brandName 열의 값을 매개 변수 brandCode에 부여하고, 매개 변수를 제품Category라는 comboBox의Store의 매개 변수로 결과를 조회하고, 결과에서 선택한 comboBox 값에 대응하는 divisionCode 필드 값을 Grid의 divisionCode 열에 부여하며,comboBox에 대응하는itemCategoryCode 필드 값을 Grid의 divisionCode 열에 부여합니다.
itemCategoryCode 열!
 
 
var productCategory=new dnet.base.AbstractCombo({
	 _dataProviderFields_:ItemMaster.ProductCategory$Model
	,storeUrl:"/ItemMasterManagement/getField.action?field=ProductCategory",tpl:ItemMaster.tpl
	,valueField:ItemMaster.valueField,displayField:ItemMaster.displayField
	,queryParam:ItemMaster.queryParam
	,callFromGrid:p
	,paramMapping:[{param:'brandCode',field:'brandName'}]
	,fieldMapping:[{field:'divisionCode',column:'divisionCode'},{field:'itemCategoryCode',column:'itemCategoryCode'}]
});
productCategory._createStore_();

좋은 웹페이지 즐겨찾기