68af07bcac2d5ffa4f43cb52c0e64a03a0c93318
[roojs1] / Roo / form / ComboBoxArray.js
1 /*
2  * Copyright(c) 2010-2012, Roo J Solutions Limited
3  *
4  * Licence LGPL
5  *
6  */
7
8 /**
9  * @class Roo.form.ComboBoxArray
10  * @extends Roo.form.TextField
11  * A facebook style adder... for lists of email / people / countries  etc...
12  * pick multiple items from a combo box, and shows each one.
13  *
14  *  Fred [x]  Brian [x]  [Pick another |v]
15  *
16  *
17  *  For this to work: it needs various extra information
18  *    - normal combo problay has
19  *      name, hiddenName
20  *    + displayField, valueField
21  *
22  *    For our purpose...
23  *
24  *
25  *   If we change from 'extends' to wrapping...
26  *   
27  *  
28  *
29  
30  
31  * @constructor
32  * Create a new ComboBoxArray.
33  * @param {Object} config Configuration options
34  */
35  
36
37 Roo.form.ComboBoxArray = function(config)
38 {
39     this.addEvents({
40         /**
41          * @event beforeremove
42          * Fires before remove the value from the list
43              * @param {Roo.form.ComboBoxArray} _self This combo box array
44              * @param {Roo.form.ComboBoxArray.Item} item removed item
45              */
46         'beforeremove' : true,
47         /**
48          * @event remove
49          * Fires when remove the value from the list
50              * @param {Roo.form.ComboBoxArray} _self This combo box array
51              * @param {Roo.form.ComboBoxArray.Item} item removed item
52              */
53         'remove' : true
54         
55         
56     });
57     
58     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
59     
60     this.items = new Roo.util.MixedCollection(false);
61     
62     // construct the child combo...
63     
64     
65     
66     
67    
68     
69 }
70
71  
72 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
73
74     /**
75      * @cfg {Roo.form.Combo} combo The combo box that is wrapped
76      */
77     
78     lastData : false,
79     
80     // behavies liek a hiddne field
81     inputType:      'hidden',
82     /**
83      * @cfg {Number} width The width of the box that displays the selected element
84      */ 
85     width:          300,
86
87     
88     
89     /**
90      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
91      */
92     name : false,
93     /**
94      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
95      */
96     hiddenName : false,
97       /**
98      * @cfg {String} seperator    The value seperator normally ',' 
99      */
100     seperator : ',',
101     
102     // private the array of items that are displayed..
103     items  : false,
104     // private - the hidden field el.
105     hiddenEl : false,
106     // private - the filed el..
107     el : false,
108     
109     //validateValue : function() { return true; }, // all values are ok!
110     //onAddClick: function() { },
111     
112     onRender : function(ct, position) 
113     {
114         
115         // create the standard hidden element
116         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
117         
118         
119         // give fake names to child combo;
120         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
121         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
122         
123         this.combo = Roo.factory(this.combo, Roo.form);
124         this.combo.onRender(ct, position);
125         if (typeof(this.combo.width) != 'undefined') {
126             this.combo.onResize(this.combo.width,0);
127         }
128         
129         this.combo.initEvents();
130         
131         // assigned so form know we need to do this..
132         this.store          = this.combo.store;
133         this.valueField     = this.combo.valueField;
134         this.displayField   = this.combo.displayField ;
135         
136         
137         this.combo.wrap.addClass('x-cbarray-grp');
138         
139         var cbwrap = this.combo.wrap.createChild(
140             {tag: 'div', cls: 'x-cbarray-cb'},
141             this.combo.el.dom
142         );
143         
144              
145         this.hiddenEl = this.combo.wrap.createChild({
146             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
147         });
148         this.el = this.combo.wrap.createChild({
149             tag: 'input',  type:'hidden' , name: this.name, value : ''
150         });
151          //   this.el.dom.removeAttribute("name");
152         
153         
154         this.outerWrap = this.combo.wrap;
155         this.wrap = cbwrap;
156         
157         this.outerWrap.setWidth(this.width);
158         this.outerWrap.dom.removeChild(this.el.dom);
159         
160         this.wrap.dom.appendChild(this.el.dom);
161         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
162         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
163         
164         this.combo.trigger.setStyle('position','relative');
165         this.combo.trigger.setStyle('left', '0px');
166         this.combo.trigger.setStyle('top', '2px');
167         
168         this.combo.el.setStyle('vertical-align', 'text-bottom');
169         
170         //this.trigger.setStyle('vertical-align', 'top');
171         
172         // this should use the code from combo really... on('add' ....)
173         if (this.adder) {
174             
175         
176             this.adder = this.outerWrap.createChild(
177                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
178             var _t = this;
179             this.adder.on('click', function(e) {
180                 _t.fireEvent('adderclick', this, e);
181             }, _t);
182         }
183         //var _t = this;
184         //this.adder.on('click', this.onAddClick, _t);
185         
186         
187         this.combo.on('select', function(cb, rec, ix) {
188             this.addItem(rec.data);
189             
190             cb.setValue('');
191             cb.el.dom.value = '';
192             //cb.lastData = rec.data;
193             // add to list
194             
195         }, this);
196         
197         
198     },
199     
200     
201     getName: function()
202     {
203         // returns hidden if it's set..
204         if (!this.rendered) {return ''};
205         return  this.hiddenName ? this.hiddenName : this.name;
206         
207     },
208     
209     
210     onResize: function(w, h){
211         
212         return;
213         // not sure if this is needed..
214         //this.combo.onResize(w,h);
215         
216         if(typeof w != 'number'){
217             // we do not handle it!?!?
218             return;
219         }
220         var tw = this.combo.trigger.getWidth();
221         tw += this.addicon ? this.addicon.getWidth() : 0;
222         tw += this.editicon ? this.editicon.getWidth() : 0;
223         var x = w - tw;
224         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
225             
226         this.combo.trigger.setStyle('left', '0px');
227         
228         if(this.list && this.listWidth === undefined){
229             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
230             this.list.setWidth(lw);
231             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
232         }
233         
234     
235         
236     },
237     
238     addItem: function(rec)
239     {
240         var valueField = this.combo.valueField;
241         var displayField = this.combo.displayField;
242         
243         if (this.items.indexOfKey(rec[valueField]) > -1) {
244             //console.log("GOT " + rec.data.id);
245             return;
246         }
247         
248         var x = new Roo.form.ComboBoxArray.Item({
249             //id : rec[this.idField],
250             data : rec,
251             displayField : displayField ,
252             tipField : displayField ,
253             cb : this
254         });
255         // use the 
256         this.items.add(rec[valueField],x);
257         // add it before the element..
258         this.updateHiddenEl();
259         x.render(this.outerWrap, this.wrap.dom);
260         // add the image handler..
261     },
262     
263     updateHiddenEl : function()
264     {
265         this.validate();
266         if (!this.hiddenEl) {
267             return;
268         }
269         var ar = [];
270         var idField = this.combo.valueField;
271         
272         this.items.each(function(f) {
273             ar.push(f.data[idField]);
274         });
275         this.hiddenEl.dom.value = ar.join(this.seperator);
276         this.validate();
277     },
278     
279     reset : function()
280     {
281         this.items.clear();
282         
283         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
284            el.remove();
285         });
286         
287         this.el.dom.value = '';
288         if (this.hiddenEl) {
289             this.hiddenEl.dom.value = '';
290         }
291         
292     },
293     getValue: function()
294     {
295         return this.hiddenEl ? this.hiddenEl.dom.value : '';
296     },
297     setValue: function(v) // not a valid action - must use addItems..
298     {
299         
300         this.reset();
301          
302         if (this.store.isLocal && (typeof(v) == 'string')) {
303             // then we can use the store to find the values..
304             // comma seperated at present.. this needs to allow JSON based encoding..
305             this.hiddenEl.value  = v;
306             var v_ar = [];
307             Roo.each(v.split(this.seperator), function(k) {
308                 Roo.log("CHECK " + this.valueField + ',' + k);
309                 var li = this.store.query(this.valueField, k);
310                 if (!li.length) {
311                     return;
312                 }
313                 var add = {};
314                 add[this.valueField] = k;
315                 add[this.displayField] = li.item(0).data[this.displayField];
316                 
317                 this.addItem(add);
318             }, this) 
319              
320         }
321         if (typeof(v) == 'object' ) {
322             // then let's assume it's an array of objects..
323             Roo.each(v, function(l) {
324                 this.addItem(l);
325             }, this);
326              
327         }
328         
329         
330     },
331     setFromData: function(v)
332     {
333         // this recieves an object, if setValues is called.
334         this.reset();
335         this.el.dom.value = v[this.displayField];
336         this.hiddenEl.dom.value = v[this.valueField];
337         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
338             return;
339         }
340         var kv = v[this.valueField];
341         var dv = v[this.displayField];
342         kv = typeof(kv) != 'string' ? '' : kv;
343         dv = typeof(dv) != 'string' ? '' : dv;
344         
345         
346         var keys = kv.split(this.seperator);
347         var display = dv.split(this.seperator);
348         for (var i = 0 ; i < keys.length; i++) {
349             add = {};
350             add[this.valueField] = keys[i];
351             add[this.displayField] = display[i];
352             this.addItem(add);
353         }
354       
355         
356     },
357     
358     /**
359      * Validates the combox array value
360      * @return {Boolean} True if the value is valid, else false
361      */
362     validate : function(){
363         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
364             this.clearInvalid();
365             return true;
366         }
367         return false;
368     },
369     
370     validateValue : function(value){
371         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
372         
373     },
374     
375     /*@
376      * overide
377      * 
378      */
379     isDirty : function() {
380         if(this.disabled) {
381             return false;
382         }
383         
384         try {
385             var d = Roo.decode(String(this.originalValue));
386         } catch (e) {
387             return String(this.getValue()) !== String(this.originalValue);
388         }
389         
390         var originalValue = [];
391         
392         for (var i = 0; i < d.length; i++){
393             originalValue.push(d[i][this.valueField]);
394         }
395         
396         return String(this.getValue()) !== String(originalValue.join(this.seperator));
397         
398     }
399     
400 });
401
402
403
404 /**
405  * @class Roo.form.ComboBoxArray.Item
406  * @extends Roo.BoxComponent
407  * A selected item in the list
408  *  Fred [x]  Brian [x]  [Pick another |v]
409  * 
410  * @constructor
411  * Create a new item.
412  * @param {Object} config Configuration options
413  */
414  
415 Roo.form.ComboBoxArray.Item = function(config) {
416     config.id = Roo.id();
417     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
418 }
419
420 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
421     data : {},
422     cb: false,
423     displayField : false,
424     tipField : false,
425     
426     
427     defaultAutoCreate : {
428         tag: 'div',
429         cls: 'x-cbarray-item',
430         cn : [ 
431             { tag: 'div' },
432             {
433                 tag: 'img',
434                 width:16,
435                 height : 16,
436                 src : Roo.BLANK_IMAGE_URL ,
437                 align: 'center'
438             }
439         ]
440         
441     },
442     
443  
444     onRender : function(ct, position)
445     {
446         Roo.form.Field.superclass.onRender.call(this, ct, position);
447         
448         if(!this.el){
449             var cfg = this.getAutoCreate();
450             this.el = ct.createChild(cfg, position);
451         }
452         
453         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
454         
455         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
456             this.cb.renderer(this.data) :
457             String.format('{0}',this.data[this.displayField]);
458         
459             
460         this.el.child('div').dom.setAttribute('qtip',
461                         String.format('{0}',this.data[this.tipField])
462         );
463         
464         this.el.child('img').on('click', this.remove, this);
465         
466     },
467    
468     remove : function()
469     {
470         if(this.cb.disabled){
471             return;
472         }
473         
474         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
475             this.cb.items.remove(this);
476             this.el.child('img').un('click', this.remove, this);
477             this.el.remove();
478             this.cb.updateHiddenEl();
479
480             this.cb.fireEvent('remove', this.cb, this);
481         }
482         
483     }
484 });