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