MultiSelect.js 13 KB

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