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