Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / docs / source / BelongsToAssociation.html
1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.BelongsToAssociation'>/**
2 </span> * @author Ed Spencer
3  * @class Ext.data.BelongsToAssociation
4  * @extends Ext.data.Association
5  *
6  * &lt;p&gt;Represents a many to one association with another model. The owner model is expected to have
7  * a foreign key which references the primary key of the associated model:&lt;/p&gt;
8  *
9 &lt;pre&gt;&lt;code&gt;
10 Ext.define('Category', {
11     extend: 'Ext.data.Model',
12     fields: [
13         {name: 'id',   type: 'int'},
14         {name: 'name', type: 'string'}
15     ]
16 });
17
18 Ext.define('Product', {
19     extend: 'Ext.data.Model',
20     fields: [
21         {name: 'id',          type: 'int'},
22         {name: 'category_id', type: 'int'},
23         {name: 'name',        type: 'string'}
24     ],
25     // we can use the belongsTo shortcut on the model to create a belongsTo association
26     belongsTo: {type: 'belongsTo', model: 'Category'}
27 });
28 &lt;/code&gt;&lt;/pre&gt;
29  * &lt;p&gt;In the example above we have created models for Products and Categories, and linked them together
30  * by saying that each Product belongs to a Category. This automatically links each Product to a Category
31  * based on the Product's category_id, and provides new functions on the Product model:&lt;/p&gt;
32  *
33  * &lt;p&gt;&lt;u&gt;Generated getter function&lt;/u&gt;&lt;/p&gt;
34  *
35  * &lt;p&gt;The first function that is added to the owner model is a getter function:&lt;/p&gt;
36  *
37 &lt;pre&gt;&lt;code&gt;
38 var product = new Product({
39     id: 100,
40     category_id: 20,
41     name: 'Sneakers'
42 });
43
44 product.getCategory(function(category, operation) {
45     //do something with the category object
46     alert(category.get('id')); //alerts 20
47 }, this);
48 &lt;/code&gt;&lt;/pre&gt;
49 *
50  * &lt;p&gt;The getCategory function was created on the Product model when we defined the association. This uses the
51  * Category's configured {@link Ext.data.proxy.Proxy proxy} to load the Category asynchronously, calling the provided
52  * callback when it has loaded.&lt;/p&gt;
53  *
54  * &lt;p&gt;The new getCategory function will also accept an object containing success, failure and callback properties
55  * - callback will always be called, success will only be called if the associated model was loaded successfully
56  * and failure will only be called if the associatied model could not be loaded:&lt;/p&gt;
57  *
58 &lt;pre&gt;&lt;code&gt;
59 product.getCategory({
60     callback: function(category, operation) {}, //a function that will always be called
61     success : function(category, operation) {}, //a function that will only be called if the load succeeded
62     failure : function(category, operation) {}, //a function that will only be called if the load did not succeed
63     scope   : this //optionally pass in a scope object to execute the callbacks in
64 });
65 &lt;/code&gt;&lt;/pre&gt;
66  *
67  * &lt;p&gt;In each case above the callbacks are called with two arguments - the associated model instance and the
68  * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is
69  * useful when the instance could not be loaded.&lt;/p&gt;
70  *
71  * &lt;p&gt;&lt;u&gt;Generated setter function&lt;/u&gt;&lt;/p&gt;
72  *
73  * &lt;p&gt;The second generated function sets the associated model instance - if only a single argument is passed to
74  * the setter then the following two calls are identical:&lt;/p&gt;
75  *
76 &lt;pre&gt;&lt;code&gt;
77 //this call
78 product.setCategory(10);
79
80 //is equivalent to this call:
81 product.set('category_id', 10);
82 &lt;/code&gt;&lt;/pre&gt;
83  * &lt;p&gt;If we pass in a second argument, the model will be automatically saved and the second argument passed to
84  * the owner model's {@link Ext.data.Model#save save} method:&lt;/p&gt;
85 &lt;pre&gt;&lt;code&gt;
86 product.setCategory(10, function(product, operation) {
87     //the product has been saved
88     alert(product.get('category_id')); //now alerts 10
89 });
90
91 //alternative syntax:
92 product.setCategory(10, {
93     callback: function(product, operation), //a function that will always be called
94     success : function(product, operation), //a function that will only be called if the load succeeded
95     failure : function(product, operation), //a function that will only be called if the load did not succeed
96     scope   : this //optionally pass in a scope object to execute the callbacks in
97 })
98 &lt;/code&gt;&lt;/pre&gt;
99 *
100  * &lt;p&gt;&lt;u&gt;Customisation&lt;/u&gt;&lt;/p&gt;
101  *
102  * &lt;p&gt;Associations reflect on the models they are linking to automatically set up properties such as the
103  * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified:&lt;/p&gt;
104  *
105 &lt;pre&gt;&lt;code&gt;
106 Ext.define('Product', {
107     fields: [...],
108
109     associations: [
110         {type: 'belongsTo', model: 'Category', primaryKey: 'unique_id', foreignKey: 'cat_id'}
111     ]
112 });
113  &lt;/code&gt;&lt;/pre&gt;
114  *
115  * &lt;p&gt;Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'category_id')
116  * with our own settings. Usually this will not be needed.&lt;/p&gt;
117  */
118 Ext.define('Ext.data.BelongsToAssociation', {
119     extend: 'Ext.data.Association',
120
121     alias: 'association.belongsto',
122
123 <span id='Ext-data.BelongsToAssociation-cfg-foreignKey'>    /**
124 </span>     * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated
125      * model. Defaults to the lowercased name of the associated model plus &quot;_id&quot;, e.g. an association with a
126      * model called Product would set up a product_id foreign key.
127      * &lt;pre&gt;&lt;code&gt;
128 Ext.define('Order', {
129     extend: 'Ext.data.Model',
130     fields: ['id', 'date'],
131     hasMany: 'Product'
132 });
133
134 Ext.define('Product', {
135     extend: 'Ext.data.Model',
136     fields: ['id', 'name', 'order_id'], // refers to the id of the order that this product belongs to
137     belongsTo: 'Group'
138 });
139 var product = new Product({
140     id: 1,
141     name: 'Product 1',
142     order_id: 22
143 }, 1);
144 product.getOrder(); // Will make a call to the server asking for order_id 22
145
146      * &lt;/code&gt;&lt;/pre&gt;
147      */
148
149 <span id='Ext-data.BelongsToAssociation-cfg-getterName'>    /**
150 </span>     * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype.
151      * Defaults to 'get' + the name of the foreign model, e.g. getCategory
152      */
153
154 <span id='Ext-data.BelongsToAssociation-cfg-setterName'>    /**
155 </span>     * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype.
156      * Defaults to 'set' + the name of the foreign model, e.g. setCategory
157      */
158     
159 <span id='Ext-data.BelongsToAssociation-cfg-type'>    /**
160 </span>     * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
161      * Use 'belongsTo' to create a HasManyAssocation
162      * &lt;pre&gt;&lt;code&gt;
163 associations: [{
164     type: 'belongsTo',
165     model: 'User'
166 }]
167      * &lt;/code&gt;&lt;/pre&gt;
168      */
169
170     constructor: function(config) {
171         this.callParent(arguments);
172
173         var me             = this,
174             ownerProto     = me.ownerModel.prototype,
175             associatedName = me.associatedName,
176             getterName     = me.getterName || 'get' + associatedName,
177             setterName     = me.setterName || 'set' + associatedName;
178
179         Ext.applyIf(me, {
180             name        : associatedName,
181             foreignKey  : associatedName.toLowerCase() + &quot;_id&quot;,
182             instanceName: associatedName + 'BelongsToInstance',
183             associationKey: associatedName.toLowerCase()
184         });
185
186         ownerProto[getterName] = me.createGetter();
187         ownerProto[setterName] = me.createSetter();
188     },
189
190 <span id='Ext-data.BelongsToAssociation-method-createSetter'>    /**
191 </span>     * @private
192      * Returns a setter function to be placed on the owner model's prototype
193      * @return {Function} The setter function
194      */
195     createSetter: function() {
196         var me              = this,
197             ownerModel      = me.ownerModel,
198             associatedModel = me.associatedModel,
199             foreignKey      = me.foreignKey,
200             primaryKey      = me.primaryKey;
201
202         //'this' refers to the Model instance inside this function
203         return function(value, options, scope) {
204             this.set(foreignKey, value);
205
206             if (typeof options == 'function') {
207                 options = {
208                     callback: options,
209                     scope: scope || this
210                 };
211             }
212
213             if (Ext.isObject(options)) {
214                 return this.save(options);
215             }
216         };
217     },
218
219 <span id='Ext-data.BelongsToAssociation-method-createGetter'>    /**
220 </span>     * @private
221      * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance
222      * the first time it is loaded so that subsequent calls to the getter always receive the same reference.
223      * @return {Function} The getter function
224      */
225     createGetter: function() {
226         var me              = this,
227             ownerModel      = me.ownerModel,
228             associatedName  = me.associatedName,
229             associatedModel = me.associatedModel,
230             foreignKey      = me.foreignKey,
231             primaryKey      = me.primaryKey,
232             instanceName    = me.instanceName;
233
234         //'this' refers to the Model instance inside this function
235         return function(options, scope) {
236             options = options || {};
237
238             var foreignKeyId = this.get(foreignKey),
239                 instance, callbackFn;
240
241             if (this[instanceName] === undefined) {
242                 instance = Ext.ModelManager.create({}, associatedName);
243                 instance.set(primaryKey, foreignKeyId);
244
245                 if (typeof options == 'function') {
246                     options = {
247                         callback: options,
248                         scope: scope || this
249                     };
250                 }
251
252                 associatedModel.load(foreignKeyId, options);
253             } else {
254                 instance = this[instanceName];
255
256                 //TODO: We're duplicating the callback invokation code that the instance.load() call above
257                 //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer
258                 //instead of the association layer.
259                 if (typeof options == 'function') {
260                     options.call(scope || this, instance);
261                 }
262
263                 if (options.success) {
264                     options.success.call(scope || this, instance);
265                 }
266
267                 if (options.callback) {
268                     options.callback.call(scope || this, instance);
269                 }
270
271                 return instance;
272             }
273         };
274     },
275
276 <span id='Ext-data.BelongsToAssociation-method-read'>    /**
277 </span>     * Read associated data
278      * @private
279      * @param {Ext.data.Model} record The record we're writing to
280      * @param {Ext.data.reader.Reader} reader The reader for the associated model
281      * @param {Object} associationData The raw associated data
282      */
283     read: function(record, reader, associationData){
284         record[this.instanceName] = reader.read([associationData]).records[0];
285     }
286 });
287 </pre></pre></body></html>