Upgrade to ExtJS 3.3.0 - Released 10/06/2010
[extjs.git] / docs / source / CompositeField.html
1 <html>
2 <head>
3   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
4   <title>The source code</title>
5     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
6     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
7 </head>
8 <body  onload="prettyPrint();">
9     <pre class="prettyprint lang-js">/*!
10  * Ext JS Library 3.3.0
11  * Copyright(c) 2006-2010 Ext JS, Inc.
12  * licensing@extjs.com
13  * http://www.extjs.com/license
14  */
15 <div id="cls-Ext.form.CompositeField"></div>/**
16  * @class Ext.form.CompositeField
17  * @extends Ext.form.Field
18  * Composite field allowing a number of form Fields to be rendered on the same row. The fields are rendered
19  * using an hbox layout internally, so all of the normal HBox layout config items are available. Example usage:
20  * <pre>
21 {
22     xtype: 'compositefield',
23     labelWidth: 120
24     items: [
25         {
26             xtype     : 'textfield',
27             fieldLabel: 'Title',
28             width     : 20
29         },
30         {
31             xtype     : 'textfield',
32             fieldLabel: 'First',
33             flex      : 1
34         },
35         {
36             xtype     : 'textfield',
37             fieldLabel: 'Last',
38             flex      : 1
39         }
40     ]
41 }
42  * </pre>
43  * In the example above the composite's fieldLabel will be set to 'Title, First, Last' as it groups the fieldLabels
44  * of each of its children. This can be overridden by setting a fieldLabel on the compositefield itself:
45  * <pre>
46 {
47     xtype: 'compositefield',
48     fieldLabel: 'Custom label',
49     items: [...]
50 }
51  * </pre>
52  * Any Ext.form.* component can be placed inside a composite field.
53  */
54 Ext.form.CompositeField = Ext.extend(Ext.form.Field, {
55
56     <div id="prop-Ext.form.CompositeField-defaultMargins"></div>/**
57      * @property defaultMargins
58      * @type String
59      * The margins to apply by default to each field in the composite
60      */
61     defaultMargins: '0 5 0 0',
62
63     <div id="prop-Ext.form.CompositeField-skipLastItemMargin"></div>/**
64      * @property skipLastItemMargin
65      * @type Boolean
66      * If true, the defaultMargins are not applied to the last item in the composite field set (defaults to true)
67      */
68     skipLastItemMargin: true,
69
70     <div id="prop-Ext.form.CompositeField-isComposite"></div>/**
71      * @property isComposite
72      * @type Boolean
73      * Signifies that this is a Composite field
74      */
75     isComposite: true,
76
77     <div id="prop-Ext.form.CompositeField-combineErrors"></div>/**
78      * @property combineErrors
79      * @type Boolean
80      * True to combine errors from the individual fields into a single error message at the CompositeField level (defaults to true)
81      */
82     combineErrors: true,
83     
84     <div id="cfg-Ext.form.CompositeField-labelConnector"></div>/**
85      * @cfg {String} labelConnector The string to use when joining segments of the built label together (defaults to ', ')
86      */
87     labelConnector: ', ',
88     
89     <div id="cfg-Ext.form.CompositeField-defaults"></div>/**
90      * @cfg {Object} defaults Any default properties to assign to the child fields.
91      */
92
93     //inherit docs
94     //Builds the composite field label
95     initComponent: function() {
96         var labels = [],
97             items  = this.items,
98             item;
99
100         for (var i=0, j = items.length; i < j; i++) {
101             item = items[i];
102
103             labels.push(item.fieldLabel);
104
105             //apply any defaults
106             Ext.applyIf(item, this.defaults);
107
108             //apply default margins to each item except the last
109             if (!(i == j - 1 && this.skipLastItemMargin)) {
110                 Ext.applyIf(item, {margins: this.defaultMargins});
111             }
112         }
113
114         this.fieldLabel = this.fieldLabel || this.buildLabel(labels);
115
116         <div id="prop-Ext.form.CompositeField-fieldErrors"></div>/**
117          * @property fieldErrors
118          * @type Ext.util.MixedCollection
119          * MixedCollection of current errors on the Composite's subfields. This is used internally to track when
120          * to show and hide error messages at the Composite level. Listeners are attached to the MixedCollection's
121          * add, remove and replace events to update the error icon in the UI as errors are added or removed.
122          */
123         this.fieldErrors = new Ext.util.MixedCollection(true, function(item) {
124             return item.field;
125         });
126
127         this.fieldErrors.on({
128             scope  : this,
129             add    : this.updateInvalidMark,
130             remove : this.updateInvalidMark,
131             replace: this.updateInvalidMark
132         });
133
134         Ext.form.CompositeField.superclass.initComponent.apply(this, arguments);
135         
136         this.innerCt = new Ext.Container({
137             layout  : 'hbox',
138             items   : this.items,
139             cls     : 'x-form-composite',
140             defaultMargins: '0 3 0 0'
141         });
142         
143         var fields = this.innerCt.findBy(function(c) {
144             return c.isFormField;
145         }, this);
146
147         <div id="prop-Ext.form.CompositeField-items"></div>/**
148          * @property items
149          * @type Ext.util.MixedCollection
150          * Internal collection of all of the subfields in this Composite
151          */
152         this.items = new Ext.util.MixedCollection();
153         this.items.addAll(fields);
154         
155     },
156
157     /**
158      * @private
159      * Creates an internal container using hbox and renders the fields to it
160      */
161     onRender: function(ct, position) {
162         if (!this.el) {
163             <div id="prop-Ext.form.CompositeField-innerCt"></div>/**
164              * @property innerCt
165              * @type Ext.Container
166              * A container configured with hbox layout which is responsible for laying out the subfields
167              */
168             var innerCt = this.innerCt;
169             innerCt.render(ct);
170
171             this.el = innerCt.getEl();
172
173             //if we're combining subfield errors into a single message, override the markInvalid and clearInvalid
174             //methods of each subfield and show them at the Composite level instead
175             if (this.combineErrors) {
176                 this.eachItem(function(field) {
177                     Ext.apply(field, {
178                         markInvalid : this.onFieldMarkInvalid.createDelegate(this, [field], 0),
179                         clearInvalid: this.onFieldClearInvalid.createDelegate(this, [field], 0)
180                     });
181                 });
182             }
183
184             //set the label 'for' to the first item
185             var l = this.el.parent().parent().child('label', true);
186             if (l) {
187                 l.setAttribute('for', this.items.items[0].id);
188             }
189         }
190
191         Ext.form.CompositeField.superclass.onRender.apply(this, arguments);
192     },
193
194     <div id="method-Ext.form.CompositeField-onFieldMarkInvalid"></div>/**
195      * Called if combineErrors is true and a subfield's markInvalid method is called.
196      * By default this just adds the subfield's error to the internal fieldErrors MixedCollection
197      * @param {Ext.form.Field} field The field that was marked invalid
198      * @param {String} message The error message
199      */
200     onFieldMarkInvalid: function(field, message) {
201         var name  = field.getName(),
202             error = {
203                 field: name, 
204                 errorName: field.fieldLabel || name,
205                 error: message
206             };
207
208         this.fieldErrors.replace(name, error);
209
210         field.el.addClass(field.invalidClass);
211     },
212
213     <div id="method-Ext.form.CompositeField-onFieldClearInvalid"></div>/**
214      * Called if combineErrors is true and a subfield's clearInvalid method is called.
215      * By default this just updates the internal fieldErrors MixedCollection.
216      * @param {Ext.form.Field} field The field that was marked invalid
217      */
218     onFieldClearInvalid: function(field) {
219         this.fieldErrors.removeKey(field.getName());
220
221         field.el.removeClass(field.invalidClass);
222     },
223
224     /**
225      * @private
226      * Called after a subfield is marked valid or invalid, this checks to see if any of the subfields are
227      * currently invalid. If any subfields are invalid it builds a combined error message marks the composite
228      * invalid, otherwise clearInvalid is called
229      */
230     updateInvalidMark: function() {
231         var ieStrict = Ext.isIE6 && Ext.isStrict;
232
233         if (this.fieldErrors.length == 0) {
234             this.clearInvalid();
235
236             //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
237             if (ieStrict) {
238                 this.clearInvalid.defer(50, this);
239             }
240         } else {
241             var message = this.buildCombinedErrorMessage(this.fieldErrors.items);
242
243             this.sortErrors();
244             this.markInvalid(message);
245
246             //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
247             if (ieStrict) {
248                 this.markInvalid(message);
249             }
250         }
251     },
252
253     <div id="method-Ext.form.CompositeField-validateValue"></div>/**
254      * Performs validation checks on each subfield and returns false if any of them fail validation.
255      * @return {Boolean} False if any subfield failed validation
256      */
257     validateValue: function() {
258         var valid = true;
259
260         this.eachItem(function(field) {
261             if (!field.isValid()) valid = false;
262         });
263
264         return valid;
265     },
266
267     <div id="method-Ext.form.CompositeField-buildCombinedErrorMessage"></div>/**
268      * Takes an object containing error messages for contained fields, returning a combined error
269      * string (defaults to just placing each item on a new line). This can be overridden to provide
270      * custom combined error message handling.
271      * @param {Array} errors Array of errors in format: [{field: 'title', error: 'some error'}]
272      * @return {String} The combined error message
273      */
274     buildCombinedErrorMessage: function(errors) {
275         var combined = [],
276             error;
277
278         for (var i = 0, j = errors.length; i < j; i++) {
279             error = errors[i];
280
281             combined.push(String.format("{0}: {1}", error.errorName, error.error));
282         }
283
284         return combined.join("<br />");
285     },
286
287     <div id="method-Ext.form.CompositeField-sortErrors"></div>/**
288      * Sorts the internal fieldErrors MixedCollection by the order in which the fields are defined.
289      * This is called before displaying errors to ensure that the errors are presented in the expected order.
290      * This function can be overridden to provide a custom sorting order if needed.
291      */
292     sortErrors: function() {
293         var fields = this.items;
294
295         this.fieldErrors.sort("ASC", function(a, b) {
296             var findByName = function(key) {
297                 return function(field) {
298                     return field.getName() == key;
299                 };
300             };
301
302             var aIndex = fields.findIndexBy(findByName(a.field)),
303                 bIndex = fields.findIndexBy(findByName(b.field));
304
305             return aIndex < bIndex ? -1 : 1;
306         });
307     },
308
309     <div id="method-Ext.form.CompositeField-reset"></div>/**
310      * Resets each field in the composite to their previous value
311      */
312     reset: function() {
313         this.eachItem(function(item) {
314             item.reset();
315         });
316
317         // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
318         // Important because reset is being called on both the group and the individual items.
319         (function() {
320             this.clearInvalid();
321         }).defer(50, this);
322     },
323     
324     <div id="method-Ext.form.CompositeField-clearInvalidChildren"></div>/**
325      * Calls clearInvalid on all child fields. This is a convenience function and should not often need to be called
326      * as fields usually take care of clearing themselves
327      */
328     clearInvalidChildren: function() {
329         this.eachItem(function(item) {
330             item.clearInvalid();
331         });
332     },
333
334     <div id="method-Ext.form.CompositeField-buildLabel"></div>/**
335      * Builds a label string from an array of subfield labels.
336      * By default this just joins the labels together with a comma
337      * @param {Array} segments Array of each of the labels in the composite field's subfields
338      * @return {String} The built label
339      */
340     buildLabel: function(segments) {
341         return Ext.clean(segments).join(this.labelConnector);
342     },
343
344     <div id="method-Ext.form.CompositeField-isDirty"></div>/**
345      * Checks each field in the composite and returns true if any is dirty
346      * @return {Boolean} True if any field is dirty
347      */
348     isDirty: function(){
349         //override the behaviour to check sub items.
350         if (this.disabled || !this.rendered) {
351             return false;
352         }
353
354         var dirty = false;
355         this.eachItem(function(item){
356             if(item.isDirty()){
357                 dirty = true;
358                 return false;
359             }
360         });
361         return dirty;
362     },
363
364     /**
365      * @private
366      * Convenience function which passes the given function to every item in the composite
367      * @param {Function} fn The function to call
368      * @param {Object} scope Optional scope object
369      */
370     eachItem: function(fn, scope) {
371         if(this.items && this.items.each){
372             this.items.each(fn, scope || this);
373         }
374     },
375
376     /**
377      * @private
378      * Passes the resize call through to the inner panel
379      */
380     onResize: function(adjWidth, adjHeight, rawWidth, rawHeight) {
381         var innerCt = this.innerCt;
382
383         if (this.rendered && innerCt.rendered) {
384             innerCt.setSize(adjWidth, adjHeight);
385         }
386
387         Ext.form.CompositeField.superclass.onResize.apply(this, arguments);
388     },
389
390     /**
391      * @private
392      * Forces the internal container to be laid out again
393      */
394     doLayout: function(shallow, force) {
395         if (this.rendered) {
396             var innerCt = this.innerCt;
397
398             innerCt.forceLayout = this.ownerCt.forceLayout;
399             innerCt.doLayout(shallow, force);
400         }
401     },
402
403     /**
404      * @private
405      */
406     beforeDestroy: function(){
407         Ext.destroy(this.innerCt);
408
409         Ext.form.CompositeField.superclass.beforeDestroy.call(this);
410     },
411
412     //override the behaviour to check sub items.
413     setReadOnly : function(readOnly) {
414         if (readOnly == undefined) {
415             readOnly = true;
416         }
417         readOnly = !!readOnly;
418
419         if(this.rendered){
420             this.eachItem(function(item){
421                 item.setReadOnly(readOnly);
422             });
423         }
424         this.readOnly = readOnly;
425     },
426
427     onShow : function() {
428         Ext.form.CompositeField.superclass.onShow.call(this);
429         this.doLayout();
430     },
431
432     //override the behaviour to check sub items.
433     onDisable : function(){
434         this.eachItem(function(item){
435             item.disable();
436         });
437     },
438
439     //override the behaviour to check sub items.
440     onEnable : function(){
441         this.eachItem(function(item){
442             item.enable();
443         });
444     }
445 });
446
447 Ext.reg('compositefield', Ext.form.CompositeField);</pre>    
448 </body>
449 </html>