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