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