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             Roo.log([cb, rec, ix]);
179             this.addItem(rec.data);
180             
181             cb.setValue('');
182             cb.el.dom.value = '';
183             //cb.lastData = rec.data;
184             // add to list
185             
186         }, this);
187         
188         
189     },
190     
191     
192     getName: function()
193     {
194         // returns hidden if it's set..
195         if (!this.rendered) {return ''};
196         return  this.hiddenName ? this.hiddenName : this.name;
197         
198     },
199     
200     
201     onResize: function(w, h){
202         
203         return;
204         // not sure if this is needed..
205         //this.combo.onResize(w,h);
206         
207         if(typeof w != 'number'){
208             // we do not handle it!?!?
209             return;
210         }
211         var tw = this.combo.trigger.getWidth();
212         tw += this.addicon ? this.addicon.getWidth() : 0;
213         tw += this.editicon ? this.editicon.getWidth() : 0;
214         var x = w - tw;
215         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
216             
217         this.combo.trigger.setStyle('left', '0px');
218         
219         if(this.list && this.listWidth === undefined){
220             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
221             this.list.setWidth(lw);
222             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
223         }
224         
225     
226         
227     },
228     
229     addItem: function(rec)
230     {
231         var valueField = this.combo.valueField;
232         var displayField = this.combo.displayField;
233         if (this.items.indexOfKey(rec[valueField]) > -1) {
234             Roo.log("GOT Record");
235             Roo.log(this.items);
236             Roo.log(rec);
237             return;
238         }
239         
240         var x = new Roo.form.ComboBoxArray.Item({
241             //id : rec[this.idField],
242             data : rec,
243             displayField : displayField ,
244             tipField : displayField ,
245             cb : this
246         });
247         // use the 
248         this.items.add(rec[valueField],x);
249         // add it before the element..
250         this.updateHiddenEl();
251         x.render(this.outerWrap, this.wrap.dom);
252         // add the image handler..
253     },
254     
255     updateHiddenEl : function()
256     {
257         this.validate();
258         if (!this.hiddenEl) {
259             return;
260         }
261         var ar = [];
262         var idField = this.combo.valueField;
263         
264         this.items.each(function(f) {
265             ar.push(f.data[idField]);
266            
267         });
268         this.hiddenEl.dom.value = ar.join(',');
269         this.validate();
270     },
271     
272     reset : function()
273     {
274         //Roo.form.ComboBoxArray.superclass.reset.call(this); 
275         this.items.each(function(f) {
276            f.remove(); 
277         });
278         this.el.dom.value = '';
279         if (this.hiddenEl) {
280             this.hiddenEl.dom.value = '';
281         }
282         
283     },
284     getValue: function()
285     {
286         return this.hiddenEl ? this.hiddenEl.dom.value : '';
287     },
288     setValue: function(v) // not a valid action - must use addItems..
289     {
290          
291         this.reset();
292         
293         
294         
295         if (this.store.isLocal && (typeof(v) == 'string')) {
296             // then we can use the store to find the values..
297             // comma seperated at present.. this needs to allow JSON based encoding..
298             this.hiddenEl.value  = v;
299             var v_ar = [];
300             Roo.each(v.split(','), function(k) {
301                 Roo.log("CHECK " + this.valueField + ',' + k);
302                 var li = this.store.query(this.valueField, k);
303                 if (!li.length) {
304                     return;
305                 }
306                 var add = {};
307                 add[this.valueField] = k;
308                 add[this.displayField] = li.item(0).data[this.displayField];
309                 
310                 this.addItem(add);
311             }, this) 
312              
313         }
314         if (typeof(v) == 'object' ) {
315             // then let's assume it's an array of objects..
316             Roo.each(v, function(l) {
317                 this.addItem(l);
318             }, this);
319              
320         }
321         
322         
323     },
324     setFromData: function(v)
325     {
326         // this recieves an object, if setValues is called.
327         this.reset();
328         this.el.dom.value = v[this.displayField];
329         this.hiddenEl.dom.value = v[this.valueField];
330         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
331             return;
332         }
333         var kv = v[this.valueField];
334         var dv = v[this.displayField];
335         kv = typeof(kv) != 'string' ? '' : kv;
336         dv = typeof(dv) != 'string' ? '' : dv;
337         
338         
339         var keys = kv.split(',');
340         var display = dv.split(',');
341         for (var i = 0 ; i < keys.length; i++) {
342             
343             add = {};
344             add[this.valueField] = keys[i];
345             add[this.displayField] = display[i];
346             this.addItem(add);
347         }
348       
349         
350     },
351     
352     /**
353      * Validates the combox array value
354      * @return {Boolean} True if the value is valid, else false
355      */
356     validate : function(){
357         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
358             this.clearInvalid();
359             return true;
360         }
361         return false;
362     },
363     
364     validateValue : function(value){
365         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
366         
367     },
368     
369     /*@
370      * overide
371      * 
372      */
373     isDirty : function() {
374         if(this.disabled) {
375             return false;
376         }
377         
378         try {
379             var d = Roo.decode(String(this.originalValue));
380         } catch (e) {
381             return String(this.getValue()) !== String(this.originalValue);
382         }
383         
384         var originalValue = [];
385         
386         for (var i = 0; i < d.length; i++){
387             originalValue.push(d[i][this.valueField]);
388         }
389         
390         return String(this.getValue()) !== String(originalValue.join(','));
391         
392     }
393     
394 });
395
396
397
398 /**
399  * @class Roo.form.ComboBoxArray.Item
400  * @extends Roo.BoxComponent
401  * A selected item in the list
402  *  Fred [x]  Brian [x]  [Pick another |v]
403  * 
404  * @constructor
405  * Create a new item.
406  * @param {Object} config Configuration options
407  */
408  
409 Roo.form.ComboBoxArray.Item = function(config) {
410     config.id = Roo.id();
411     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
412 }
413
414 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
415     data : {},
416     cb: false,
417     displayField : false,
418     tipField : false,
419     
420     
421     defaultAutoCreate : {
422         tag: 'div',
423         cls: 'x-cbarray-item',
424         cn : [ 
425             { tag: 'div' },
426             {
427                 tag: 'img',
428                 width:16,
429                 height : 16,
430                 src : Roo.BLANK_IMAGE_URL ,
431                 align: 'center'
432             }
433         ]
434         
435     },
436     
437  
438     onRender : function(ct, position)
439     {
440         Roo.form.Field.superclass.onRender.call(this, ct, position);
441         
442         if(!this.el){
443             var cfg = this.getAutoCreate();
444             this.el = ct.createChild(cfg, position);
445         }
446         
447         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
448         
449         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
450             this.cb.renderer(this.data) :
451             String.format('{0}',this.data[this.displayField]);
452         
453             
454         this.el.child('div').dom.setAttribute('qtip',
455                         String.format('{0}',this.data[this.tipField])
456         );
457         
458         this.el.child('img').on('click', this.remove, this);
459         
460     },
461    
462     remove : function()
463     {
464         if(this.cb.disabled){
465             return;
466         }
467         this.cb.items.remove(this);
468         this.el.child('img').un('click', this.remove, this);
469         this.el.remove();
470         this.cb.updateHiddenEl();
471         
472         this.cb.fireEvent('remove', this.cb, this);
473     }
474 });