Upgrade to ExtJS 3.2.2 - Released 06/02/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.2.2
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     //inherit docs
90     //Builds the composite field label
91     initComponent: function() {
92         var labels = [],
93             items  = this.items,
94             item;
95
96         for (var i=0, j = items.length; i < j; i++) {
97             item = items[i];
98
99             labels.push(item.fieldLabel);
100
101             //apply any defaults
102             Ext.apply(item, this.defaults);
103
104             //apply default margins to each item except the last
105             if (!(i == j - 1 && this.skipLastItemMargin)) {
106                 Ext.applyIf(item, {margins: this.defaultMargins});
107             }
108         }
109
110         this.fieldLabel = this.fieldLabel || this.buildLabel(labels);
111
112         <div id="prop-Ext.form.CompositeField-fieldErrors"></div>/**
113          * @property fieldErrors
114          * @type Ext.util.MixedCollection
115          * MixedCollection of current errors on the Composite's subfields. This is used internally to track when
116          * to show and hide error messages at the Composite level. Listeners are attached to the MixedCollection's
117          * add, remove and replace events to update the error icon in the UI as errors are added or removed.
118          */
119         this.fieldErrors = new Ext.util.MixedCollection(true, function(item) {
120             return item.field;
121         });
122
123         this.fieldErrors.on({
124             scope  : this,
125             add    : this.updateInvalidMark,
126             remove : this.updateInvalidMark,
127             replace: this.updateInvalidMark
128         });
129
130         Ext.form.CompositeField.superclass.initComponent.apply(this, arguments);
131     },
132
133     /**
134      * @private
135      * Creates an internal container using hbox and renders the fields to it
136      */
137     onRender: function(ct, position) {
138         if (!this.el) {
139             <div id="prop-Ext.form.CompositeField-innerCt"></div>/**
140              * @property innerCt
141              * @type Ext.Container
142              * A container configured with hbox layout which is responsible for laying out the subfields
143              */
144             var innerCt = this.innerCt = new Ext.Container({
145                 layout  : 'hbox',
146                 renderTo: ct,
147                 items   : this.items,
148                 cls     : 'x-form-composite',
149                 defaultMargins: '0 3 0 0'
150             });
151
152             this.el = innerCt.getEl();
153
154             var fields = innerCt.findBy(function(c) {
155                 return c.isFormField;
156             }, this);
157
158             <div id="prop-Ext.form.CompositeField-items"></div>/**
159              * @property items
160              * @type Ext.util.MixedCollection
161              * Internal collection of all of the subfields in this Composite
162              */
163             this.items = new Ext.util.MixedCollection();
164             this.items.addAll(fields);
165
166             //if we're combining subfield errors into a single message, override the markInvalid and clearInvalid
167             //methods of each subfield and show them at the Composite level instead
168             if (this.combineErrors) {
169                 this.eachItem(function(field) {
170                     Ext.apply(field, {
171                         markInvalid : this.onFieldMarkInvalid.createDelegate(this, [field], 0),
172                         clearInvalid: this.onFieldClearInvalid.createDelegate(this, [field], 0)
173                     });
174                 });
175             }
176
177             //set the label 'for' to the first item
178             var l = this.el.parent().parent().child('label', true);
179             if (l) {
180                 l.setAttribute('for', this.items.items[0].id);
181             }
182         }
183
184         Ext.form.CompositeField.superclass.onRender.apply(this, arguments);
185     },
186
187     <div id="method-Ext.form.CompositeField-onFieldMarkInvalid"></div>/**
188      * Called if combineErrors is true and a subfield's markInvalid method is called.
189      * By default this just adds the subfield's error to the internal fieldErrors MixedCollection
190      * @param {Ext.form.Field} field The field that was marked invalid
191      * @param {String} message The error message
192      */
193     onFieldMarkInvalid: function(field, message) {
194         var name  = field.getName(),
195             error = {field: name, error: message};
196
197         this.fieldErrors.replace(name, error);
198
199         field.el.addClass(field.invalidClass);
200     },
201
202     <div id="method-Ext.form.CompositeField-onFieldClearInvalid"></div>/**
203      * Called if combineErrors is true and a subfield's clearInvalid method is called.
204      * By default this just updates the internal fieldErrors MixedCollection.
205      * @param {Ext.form.Field} field The field that was marked invalid
206      */
207     onFieldClearInvalid: function(field) {
208         this.fieldErrors.removeKey(field.getName());
209
210         field.el.removeClass(field.invalidClass);
211     },
212
213     /**
214      * @private
215      * Called after a subfield is marked valid or invalid, this checks to see if any of the subfields are
216      * currently invalid. If any subfields are invalid it builds a combined error message marks the composite
217      * invalid, otherwise clearInvalid is called
218      */
219     updateInvalidMark: function() {
220         var ieStrict = Ext.isIE6 && Ext.isStrict;
221
222         if (this.fieldErrors.length == 0) {
223             this.clearInvalid();
224
225             //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
226             if (ieStrict) {
227                 this.clearInvalid.defer(50, this);
228             }
229         } else {
230             var message = this.buildCombinedErrorMessage(this.fieldErrors.items);
231
232             this.sortErrors();
233             this.markInvalid(message);
234
235             //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
236             if (ieStrict) {
237                 this.markInvalid(message);
238             }
239         }
240     },
241
242     <div id="method-Ext.form.CompositeField-validateValue"></div>/**
243      * Performs validation checks on each subfield and returns false if any of them fail validation.
244      * @return {Boolean} False if any subfield failed validation
245      */
246     validateValue: function() {
247         var valid = true;
248
249         this.eachItem(function(field) {
250             if (!field.isValid()) valid = false;
251         });
252
253         return valid;
254     },
255
256     <div id="method-Ext.form.CompositeField-buildCombinedErrorMessage"></div>/**
257      * Takes an object containing error messages for contained fields, returning a combined error
258      * string (defaults to just placing each item on a new line). This can be overridden to provide
259      * custom combined error message handling.
260      * @param {Array} errors Array of errors in format: [{field: 'title', error: 'some error'}]
261      * @return {String} The combined error message
262      */
263     buildCombinedErrorMessage: function(errors) {
264         var combined = [],
265             error;
266
267         for (var i = 0, j = errors.length; i < j; i++) {
268             error = errors[i];
269
270             combined.push(String.format("{0}: {1}", error.field, error.error));
271         }
272
273         return combined.join("<br />");
274     },
275
276     <div id="method-Ext.form.CompositeField-sortErrors"></div>/**
277      * Sorts the internal fieldErrors MixedCollection by the order in which the fields are defined.
278      * This is called before displaying errors to ensure that the errors are presented in the expected order.
279      * This function can be overridden to provide a custom sorting order if needed.
280      */
281     sortErrors: function() {
282         var fields = this.items;
283
284         this.fieldErrors.sort("ASC", function(a, b) {
285             var findByName = function(key) {
286                 return function(field) {
287                     return field.getName() == key;
288                 };
289             };
290
291             var aIndex = fields.findIndexBy(findByName(a.field)),
292                 bIndex = fields.findIndexBy(findByName(b.field));
293
294             return aIndex < bIndex ? -1 : 1;
295         });
296     },
297
298     <div id="method-Ext.form.CompositeField-reset"></div>/**
299      * Resets each field in the composite to their previous value
300      */
301     reset: function() {
302         this.eachItem(function(item) {
303             item.reset();
304         });
305
306         // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
307         // Important because reset is being called on both the group and the individual items.
308         (function() {
309             this.clearInvalid();
310         }).defer(50, this);
311     },
312     
313     <div id="method-Ext.form.CompositeField-clearInvalidChildren"></div>/**
314      * Calls clearInvalid on all child fields. This is a convenience function and should not often need to be called
315      * as fields usually take care of clearing themselves
316      */
317     clearInvalidChildren: function() {
318         this.eachItem(function(item) {
319             item.clearInvalid();
320         });
321     },
322
323     <div id="method-Ext.form.CompositeField-buildLabel"></div>/**
324      * Builds a label string from an array of subfield labels.
325      * By default this just joins the labels together with a comma
326      * @param {Array} segments Array of each of the labels in the composite field's subfields
327      * @return {String} The built label
328      */
329     buildLabel: function(segments) {
330         return Ext.clean(segments).join(this.labelConnector);
331     },
332
333     <div id="method-Ext.form.CompositeField-isDirty"></div>/**
334      * Checks each field in the composite and returns true if any is dirty
335      * @return {Boolean} True if any field is dirty
336      */
337     isDirty: function(){
338         //override the behaviour to check sub items.
339         if (this.disabled || !this.rendered) {
340             return false;
341         }
342
343         var dirty = false;
344         this.eachItem(function(item){
345             if(item.isDirty()){
346                 dirty = true;
347                 return false;
348             }
349         });
350         return dirty;
351     },
352
353     /**
354      * @private
355      * Convenience function which passes the given function to every item in the composite
356      * @param {Function} fn The function to call
357      * @param {Object} scope Optional scope object
358      */
359     eachItem: function(fn, scope) {
360         if(this.items && this.items.each){
361             this.items.each(fn, scope || this);
362         }
363     },
364
365     /**
366      * @private
367      * Passes the resize call through to the inner panel
368      */
369     onResize: function(adjWidth, adjHeight, rawWidth, rawHeight) {
370         var innerCt = this.innerCt;
371
372         if (this.rendered && innerCt.rendered) {
373             innerCt.setSize(adjWidth, adjHeight);
374         }
375
376         Ext.form.CompositeField.superclass.onResize.apply(this, arguments);
377     },
378
379     /**
380      * @private
381      * Forces the internal container to be laid out again
382      */
383     doLayout: function(shallow, force) {
384         if (this.rendered) {
385             var innerCt = this.innerCt;
386
387             innerCt.forceLayout = this.ownerCt.forceLayout;
388             innerCt.doLayout(shallow, force);
389         }
390     },
391
392     /**
393      * @private
394      */
395     beforeDestroy: function(){
396         Ext.destroy(this.innerCt);
397
398         Ext.form.CompositeField.superclass.beforeDestroy.call(this);
399     },
400
401     //override the behaviour to check sub items.
402     setReadOnly : function(readOnly) {
403         readOnly = readOnly || true;
404
405         if(this.rendered){
406             this.eachItem(function(item){
407                 item.setReadOnly(readOnly);
408             });
409         }
410         this.readOnly = readOnly;
411     },
412
413     onShow : function() {
414         Ext.form.CompositeField.superclass.onShow.call(this);
415         this.doLayout();
416     },
417
418     //override the behaviour to check sub items.
419     onDisable : function(){
420         this.eachItem(function(item){
421             item.disable();
422         });
423     },
424
425     //override the behaviour to check sub items.
426     onEnable : function(){
427         this.eachItem(function(item){
428             item.enable();
429         });
430     }
431 });
432
433 Ext.reg('compositefield', Ext.form.CompositeField);
434 </pre>    
435 </body>
436 </html>