Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / examples / ux / form / MultiSelect.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.ux.form.MultiSelect
17  * @extends Ext.form.field.Base
18  * A control that allows selection and form submission of multiple list items.
19  *
20  *  @history
21  *    2008-06-19 bpm Original code contributed by Toby Stuart (with contributions from Robert Williams)
22  *    2008-06-19 bpm Docs and demo code clean up
23  *
24  * @constructor
25  * Create a new MultiSelect
26  * @param {Object} config Configuration options
27  * @xtype multiselect
28  */
29 Ext.define('Ext.ux.form.MultiSelect', {
30     extend: 'Ext.form.field.Base',
31     alternateClassName: 'Ext.ux.Multiselect',
32     alias: ['widget.multiselect', 'widget.multiselectfield'],
33     uses: [
34         'Ext.view.BoundList',
35         'Ext.form.FieldSet',
36         'Ext.ux.layout.component.form.MultiSelect',
37         'Ext.view.DragZone',
38         'Ext.view.DropZone'
39     ],
40
41     /**
42      * @cfg {String} listTitle An optional title to be displayed at the top of the selection list.
43      */
44
45     /**
46      * @cfg {String/Array} dragGroup The ddgroup name(s) for the MultiSelect DragZone (defaults to undefined).
47      */
48
49     /**
50      * @cfg {String/Array} dropGroup The ddgroup name(s) for the MultiSelect DropZone (defaults to undefined).
51      */
52
53     /**
54      * @cfg {Boolean} ddReorder Whether the items in the MultiSelect list are drag/drop reorderable (defaults to false).
55      */
56     ddReorder: false,
57
58     /**
59      * @cfg {Object/Array} tbar An optional toolbar to be inserted at the top of the control's selection list.
60      * This can be a {@link Ext.toolbar.Toolbar} object, a toolbar config, or an array of buttons/button configs
61      * to be added to the toolbar. See {@link Ext.panel.Panel#tbar}.
62      */
63
64     /**
65      * @cfg {String} appendOnly True if the list should only allow append drops when drag/drop is enabled
66      * (use for lists which are sorted, defaults to false).
67      */
68     appendOnly: false,
69
70     /**
71      * @cfg {String} displayField Name of the desired display field in the dataset (defaults to 'text').
72      */
73     displayField: 'text',
74
75     /**
76      * @cfg {String} valueField Name of the desired value field in the dataset (defaults to the
77      * value of {@link #displayField}).
78      */
79
80     /**
81      * @cfg {Boolean} allowBlank False to require at least one item in the list to be selected, true to allow no
82      * selection (defaults to true).
83      */
84     allowBlank: true,
85
86     /**
87      * @cfg {Number} minSelections Minimum number of selections allowed (defaults to 0).
88      */
89     minSelections: 0,
90
91     /**
92      * @cfg {Number} maxSelections Maximum number of selections allowed (defaults to Number.MAX_VALUE).
93      */
94     maxSelections: Number.MAX_VALUE,
95
96     /**
97      * @cfg {String} blankText Default text displayed when the control contains no items (defaults to 'This field is required')
98      */
99     blankText: 'This field is required',
100
101     /**
102      * @cfg {String} minSelectionsText Validation message displayed when {@link #minSelections} is not met (defaults to 'Minimum {0}
103      * item(s) required').  The {0} token will be replaced by the value of {@link #minSelections}.
104      */
105     minSelectionsText: 'Minimum {0} item(s) required',
106
107     /**
108      * @cfg {String} maxSelectionsText Validation message displayed when {@link #maxSelections} is not met (defaults to 'Maximum {0}
109      * item(s) allowed').  The {0} token will be replaced by the value of {@link #maxSelections}.
110      */
111     maxSelectionsText: 'Maximum {0} item(s) allowed',
112
113     /**
114      * @cfg {String} delimiter The string used to delimit the selected values when {@link #getSubmitValue submitting}
115      * the field as part of a form. Defaults to ','. If you wish to have the selected values submitted as separate
116      * parameters rather than a single delimited parameter, set this to <tt>null</tt>.
117      */
118     delimiter: ',',
119
120     /**
121      * @cfg {Ext.data.Store/Array} store The data source to which this MultiSelect is bound (defaults to <tt>undefined</tt>).
122      * Acceptable values for this property are:
123      * <div class="mdetail-params"><ul>
124      * <li><b>any {@link Ext.data.Store Store} subclass</b></li>
125      * <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally.
126      * <div class="mdetail-params"><ul>
127      * <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
128      * A 1-dimensional array will automatically be expanded (each array item will be the combo
129      * {@link #valueField value} and {@link #displayField text})</div></li>
130      * <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
131      * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
132      * {@link #valueField value}, while the value at index 1 is assumed to be the combo {@link #displayField text}.
133      * </div></li></ul></div></li></ul></div>
134      */
135
136     componentLayout: 'multiselectfield',
137
138     fieldBodyCls: Ext.baseCSSPrefix + 'form-multiselect-body',
139
140
141     // private
142     initComponent: function(){
143         var me = this;
144
145         me.bindStore(me.store, true);
146         if (me.store.autoCreated) {
147             me.valueField = me.displayField = 'field1';
148             if (!me.store.expanded) {
149                 me.displayField = 'field2';
150             }
151         }
152
153         if (!Ext.isDefined(me.valueField)) {
154             me.valueField = me.displayField;
155         }
156
157         me.callParent();
158     },
159
160     bindStore: function(store, initial) {
161         var me = this,
162             oldStore = me.store,
163             boundList = me.boundList;
164
165         if (oldStore && !initial && oldStore !== store && oldStore.autoDestroy) {
166             oldStore.destroy();
167         }
168
169         me.store = store ? Ext.data.StoreManager.lookup(store) : null;
170         if (boundList) {
171             boundList.bindStore(store || null);
172         }
173     },
174
175
176     // private
177     onRender: function(ct, position) {
178         var me = this,
179             panel, boundList, selModel;
180
181         me.callParent(arguments);
182
183         boundList = me.boundList = Ext.create('Ext.view.BoundList', {
184             multiSelect: true,
185             store: me.store,
186             displayField: me.displayField,
187             border: false
188         });
189
190         selModel = boundList.getSelectionModel();
191         me.mon(selModel, {
192             selectionChange: me.onSelectionChange,
193             scope: me
194         });
195
196         panel = me.panel = Ext.create('Ext.panel.Panel', {
197             title: me.listTitle,
198             tbar: me.tbar,
199             items: [boundList],
200             renderTo: me.bodyEl,
201             layout: 'fit'
202         });
203
204         // Must set upward link after first render
205         panel.ownerCt = me;
206
207         // Set selection to current value
208         me.setRawValue(me.rawValue);
209     },
210
211     // No content generated via template, it's all added components
212     getSubTplMarkup: function() {
213         return '';
214     },
215
216     // private
217     afterRender: function() {
218         var me = this;
219         me.callParent();
220
221         if (me.ddReorder && !me.dragGroup && !me.dropGroup){
222             me.dragGroup = me.dropGroup = 'MultiselectDD-' + Ext.id();
223         }
224
225         if (me.draggable || me.dragGroup){
226             me.dragZone = Ext.create('Ext.view.DragZone', {
227                 view: me.boundList,
228                 ddGroup: me.dragGroup,
229                 dragText: '{0} Item{1}'
230             });
231         }
232         if (me.droppable || me.dropGroup){
233             me.dropZone = Ext.create('Ext.view.DropZone', {
234                 view: me.boundList,
235                 ddGroup: me.dropGroup,
236                 handleNodeDrop: function(data, dropRecord, position) {
237                     var view = this.view,
238                         store = view.getStore(),
239                         records = data.records,
240                         index;
241
242                     // remove the Models from the source Store
243                     data.view.store.remove(records);
244
245                     index = store.indexOf(dropRecord);
246                     if (position === 'after') {
247                         index++;
248                     }
249                     store.insert(index, records);
250                     view.getSelectionModel().select(records);
251                 }
252             });
253         }
254     },
255
256     onSelectionChange: function() {
257         this.checkChange();
258     },
259
260     /**
261      * Clears any values currently selected.
262      */
263     clearValue: function() {
264         this.setValue([]);
265     },
266
267     /**
268      * Return the value(s) to be submitted for this field. The returned value depends on the {@link #delimiter}
269      * config: If it is set to a String value (like the default ',') then this will return the selected values
270      * joined by the delimiter. If it is set to <tt>null</tt> then the values will be returned as an Array.
271      */
272     getSubmitValue: function() {
273         var me = this,
274             delimiter = me.delimiter,
275             val = me.getValue();
276         return Ext.isString(delimiter) ? val.join(delimiter) : val;
277     },
278
279     // inherit docs
280     getRawValue: function() {
281         var me = this,
282             boundList = me.boundList;
283         if (boundList) {
284             me.rawValue = Ext.Array.map(boundList.getSelectionModel().getSelection(), function(model) {
285                 return model.get(me.valueField);
286             });
287         }
288         return me.rawValue;
289     },
290
291     // inherit docs
292     setRawValue: function(value) {
293         var me = this,
294             boundList = me.boundList,
295             models;
296
297         value = Ext.Array.from(value);
298         me.rawValue = value;
299
300         if (boundList) {
301             models = [];
302             Ext.Array.forEach(value, function(val) {
303                 var undef,
304                     model = me.store.findRecord(me.valueField, val, undef, undef, true, true);
305                 if (model) {
306                     models.push(model);
307                 }
308             });
309             boundList.getSelectionModel().select(models, false, true);
310         }
311
312         return value;
313     },
314
315     // no conversion
316     valueToRaw: function(value) {
317         return value;
318     },
319
320     // compare array values
321     isEqual: function(v1, v2) {
322         var fromArray = Ext.Array.from,
323             i, len;
324
325         v1 = fromArray(v1);
326         v2 = fromArray(v2);
327         len = v1.length;
328
329         if (len !== v2.length) {
330             return false;
331         }
332
333         for(i = 0; i < len; i++) {
334             if (v2[i] !== v1[i]) {
335                 return false;
336             }
337         }
338
339         return true;
340     },
341
342     getErrors : function(value) {
343         var me = this,
344             format = Ext.String.format,
345             errors = me.callParent(arguments),
346             numSelected;
347
348         value = Ext.Array.from(value || me.getValue());
349         numSelected = value.length;
350
351         if (!me.allowBlank && numSelected < 1) {
352             errors.push(me.blankText);
353         }
354         if (numSelected < this.minSelections) {
355             errors.push(format(me.minSelectionsText, me.minSelections));
356         }
357         if (numSelected > this.maxSelections) {
358             errors.push(format(me.maxSelectionsText, me.maxSelections));
359         }
360
361         return errors;
362     },
363
364     onDisable: function() {
365         this.callParent();
366         this.disabled = true;
367         this.updateReadOnly();
368     },
369
370     onEnable: function() {
371         this.callParent();
372         this.disabled = false;
373         this.updateReadOnly();
374     },
375
376     setReadOnly: function(readOnly) {
377         this.readOnly = readOnly;
378         this.updateReadOnly();
379     },
380
381     /**
382      * @private Lock or unlock the BoundList's selection model to match the current disabled/readonly state
383      */
384     updateReadOnly: function() {
385         var me = this,
386             boundList = me.boundList,
387             readOnly = me.readOnly || me.disabled;
388         if (boundList) {
389             boundList.getSelectionModel().setLocked(readOnly);
390         }
391     },
392
393     onDestroy: function(){
394         Ext.destroyMembers(this, 'panel', 'boundList', 'dragZone', 'dropZone');
395         this.callParent();
396     }
397 });
398
399
400