Upgrade to ExtJS 4.0.7 - Released 10/19/2011
[extjs.git] / examples / ux / FieldReplicator.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.ux.FieldReplicator
17  * <p>A plugin for Field Components which creates clones of the Field for as
18  * long as the user keeps filling them. Leaving the final one blank ends the repeating series.</p>
19  * <p>Usage:</p>
20  * <pre><code>
21     {
22         xtype: 'combo',
23         plugins: [ Ext.ux.FieldReplicator ],
24         triggerAction: 'all',
25         fieldLabel: 'Select recipient',
26         store: recipientStore
27     }
28  * </code></pre>
29  */
30 Ext.define('Ext.ux.FieldReplicator', {
31     singleton: true,
32
33     init: function(field) {
34         // Assign the field an id grouping it with fields cloned from it. If it already
35         // has an id that means it is itself a clone.
36         if (!field.replicatorId) {
37             field.replicatorId = Ext.id();
38         }
39
40         field.on('blur', this.onBlur, this);
41     },
42
43     onBlur: function(field) {
44         var ownerCt = field.ownerCt,
45             replicatorId = field.replicatorId,
46             isEmpty = Ext.isEmpty(field.getRawValue()),
47             siblings = ownerCt.query('[replicatorId=' + replicatorId + ']'),
48             isLastInGroup = siblings[siblings.length - 1] === field,
49             clone, idx;
50
51         // If a field before the final one was blanked out, remove it
52         if (isEmpty && !isLastInGroup) {
53             Ext.Function.defer(field.destroy, 10, field); //delay to allow tab key to move focus first
54         }
55         // If the field is the last in the list and has a value, add a cloned field after it
56         else if(!isEmpty && isLastInGroup) {
57             clone = field.cloneConfig({replicatorId: replicatorId});
58             idx = ownerCt.items.indexOf(field);
59             ownerCt.add(idx + 1, clone);
60         }
61     }
62
63 });