Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / examples / ux / FieldReplicator.js
1 /**
2  * @class Ext.ux.FieldReplicator
3  * <p>A plugin for Field Components which creates clones of the Field for as
4  * long as the user keeps filling them. Leaving the final one blank ends the repeating series.</p>
5  * <p>Usage:</p>
6  * <pre><code>
7     {
8         xtype: 'combo',
9         plugins: [ Ext.ux.FieldReplicator ],
10         triggerAction: 'all',
11         fieldLabel: 'Select recipient',
12         store: recipientStore
13     }
14  * </code></pre>
15  */
16 Ext.define('Ext.ux.FieldReplicator', {
17     singleton: true,
18
19     init: function(field) {
20         // Assign the field an id grouping it with fields cloned from it. If it already
21         // has an id that means it is itself a clone.
22         if (!field.replicatorId) {
23             field.replicatorId = Ext.id();
24         }
25
26         field.on('blur', this.onBlur, this);
27     },
28
29     onBlur: function(field) {
30         var ownerCt = field.ownerCt,
31             replicatorId = field.replicatorId,
32             isEmpty = Ext.isEmpty(field.getRawValue()),
33             siblings = ownerCt.query('[replicatorId=' + replicatorId + ']'),
34             isLastInGroup = siblings[siblings.length - 1] === field,
35             clone, idx;
36
37         // If a field before the final one was blanked out, remove it
38         if (isEmpty && !isLastInGroup) {
39             Ext.Function.defer(field.destroy, 10, field); //delay to allow tab key to move focus first
40         }
41         // If the field is the last in the list and has a value, add a cloned field after it
42         else if(!isEmpty && isLastInGroup) {
43             clone = field.cloneConfig({replicatorId: replicatorId});
44             idx = ownerCt.items.indexOf(field);
45             ownerCt.add(idx + 1, clone);
46         }
47     }
48
49 });