Home » Ext JS 技巧

[Ext]讓 ItemSelector 能透過 setValue() 來指定項目

Ext JS 中有很多很實用的擴充組件都寫在 Ext.ux 底下,像 ItemSelector 就是一個能做到常見的左右 List 互相加入移除的表單組件。雖然基本的表單都是繼承自 Ext.form.Field,不過其中還有使用到 Ext.ux.form.MultiSelect,因此才能讓我們的 ItemSelector 中的清單項目能有拖拉移動的效果。



不過雖然該有的功能都有提供了,但最基本的 setValue() 卻是不能正常運作的。像筆者想要透過程式來把左邊的清單項目移到右邊的清單就都沒有任何反應,所以筆者就覆寫 ItemSelectorsetValue() 函式,使其能正常的透過 setValue() 來指定右邊項目:

檢視原始碼 JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 覆寫 Ext.ux.form.ItemSelector 的 setValue()
Ext.override(Ext.ux.form.ItemSelector, {
	setValue: function(values) {
		var index;
		var selectionsArray = [];
		this.toMultiselect.view.clearSelections();
		this.hiddenField.dom.value = '';
 
		if (!values || (values == '')) { return; }
 
		if (!Ext.isArray(values)) { values = values.split(this.delimiter); }
		for (var i=0; i<values.length; i++) {
			index = this.fromMultiselect.view.store.indexOf(this.fromMultiselect.view.store.query(this.fromMultiselect.valueField, new RegExp('^' + values[i] + '$', "i")).itemAt(0));
			if (index > -1) {
				selectionsArray.push(index);
			}
		}
 
		var records = [], record;
		if (selectionsArray.length > 0) {
			for (var i=0; i<selectionsArray.length; i++) {
				var record = this.fromMultiselect.view.store.getAt(selectionsArray[i]);
				records.push(record);
			}
			if(!this.allowDup)selectionsArray = [];
			for (var i=0; i<records.length; i++) {
				record = records[i];
				if(this.allowDup){
					var x=new Ext.data.Record();
					record.id=x.id;
					delete x;
					this.toMultiselect.view.store.add(record);
				}else{
					this.fromMultiselect.view.store.remove(record);
					this.toMultiselect.view.store.add(record);
					selectionsArray.push((this.toMultiselect.view.store.getCount() - 1));
				}
			}
		}
		this.toMultiselect.view.refresh();
		this.fromMultiselect.view.refresh();
		var si = this.toMultiselect.store.sortInfo;
		if(si){
			this.toMultiselect.store.sort(si.field, si.direction);
		}
		this.toMultiselect.view.select(selectionsArray);
	}
});

覆寫完後,我們就能透過以下的方式來指定右邊的值

檢視原始碼 JavaScript
1
myItemSelectorObj.setValue('value1, value2, value3');

在加入右邊清單項目的同時,左邊的項目也會一併被移除,除非設定了允許重覆的屬性:allowDup

而要取值或是重設時一樣是用:

檢視原始碼 JavaScript
1
2
3
4
// 取值
myItemSelectorObj.getValue();
// 重設
myItemSelectorObj.reset();

範例瀏覽:
http://demonstration.abgne.tw/extjs_3_x/tips/0002/0002.html

1 筆針對 [Ext]讓 ItemSelector 能透過 setValue() 來指定項目 的迴響

發表迴響