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