Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / data / Model.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.Model
4  *
5  * <p>A Model represents some object that your application manages. For example, one might define a Model for Users, Products,
6  * Cars, or any other real-world object that we want to model in the system. Models are registered via the {@link Ext.ModelManager model manager},
7  * and are used by {@link Ext.data.Store stores}, which are in turn used by many of the data-bound components in Ext.</p>
8  *
9  * <p>Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:</p>
10  *
11 <pre><code>
12 Ext.define('User', {
13     extend: 'Ext.data.Model',
14     fields: [
15         {name: 'name',  type: 'string'},
16         {name: 'age',   type: 'int'},
17         {name: 'phone', type: 'string'},
18         {name: 'alive', type: 'boolean', defaultValue: true}
19     ],
20
21     changeName: function() {
22         var oldName = this.get('name'),
23             newName = oldName + " The Barbarian";
24
25         this.set('name', newName);
26     }
27 });
28 </code></pre>
29 *
30 * <p>The fields array is turned into a {@link Ext.util.MixedCollection MixedCollection} automatically by the {@link Ext.ModelManager ModelManager}, and all
31 * other functions and properties are copied to the new Model's prototype.</p>
32 *
33 * <p>Now we can create instances of our User model and call any model logic we defined:</p>
34 *
35 <pre><code>
36 var user = Ext.ModelManager.create({
37     name : 'Conan',
38     age  : 24,
39     phone: '555-555-5555'
40 }, 'User');
41
42 user.changeName();
43 user.get('name'); //returns "Conan The Barbarian"
44 </code></pre>
45  *
46  * <p><u>Validations</u></p>
47  *
48  * <p>Models have built-in support for validations, which are executed against the validator functions in
49  * {@link Ext.data.validations} ({@link Ext.data.validations see all validation functions}). Validations are easy to add to models:</p>
50  *
51 <pre><code>
52 Ext.define('User', {
53     extend: 'Ext.data.Model',
54     fields: [
55         {name: 'name',     type: 'string'},
56         {name: 'age',      type: 'int'},
57         {name: 'phone',    type: 'string'},
58         {name: 'gender',   type: 'string'},
59         {name: 'username', type: 'string'},
60         {name: 'alive',    type: 'boolean', defaultValue: true}
61     ],
62
63     validations: [
64         {type: 'presence',  field: 'age'},
65         {type: 'length',    field: 'name',     min: 2},
66         {type: 'inclusion', field: 'gender',   list: ['Male', 'Female']},
67         {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']},
68         {type: 'format',    field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}
69     ]
70 });
71 </code></pre>
72  *
73  * <p>The validations can be run by simply calling the {@link #validate} function, which returns a {@link Ext.data.Errors}
74  * object:</p>
75  *
76 <pre><code>
77 var instance = Ext.ModelManager.create({
78     name: 'Ed',
79     gender: 'Male',
80     username: 'edspencer'
81 }, 'User');
82
83 var errors = instance.validate();
84 </code></pre>
85  *
86  * <p><u>Associations</u></p>
87  *
88  * <p>Models can have associations with other Models via {@link Ext.data.BelongsToAssociation belongsTo} and
89  * {@link Ext.data.HasManyAssociation hasMany} associations. For example, let's say we're writing a blog administration
90  * application which deals with Users, Posts and Comments. We can express the relationships between these models like this:</p>
91  *
92 <pre><code>
93 Ext.define('Post', {
94     extend: 'Ext.data.Model',
95     fields: ['id', 'user_id'],
96
97     belongsTo: 'User',
98     hasMany  : {model: 'Comment', name: 'comments'}
99 });
100
101 Ext.define('Comment', {
102     extend: 'Ext.data.Model',
103     fields: ['id', 'user_id', 'post_id'],
104
105     belongsTo: 'Post'
106 });
107
108 Ext.define('User', {
109     extend: 'Ext.data.Model',
110     fields: ['id'],
111
112     hasMany: [
113         'Post',
114         {model: 'Comment', name: 'comments'}
115     ]
116 });
117 </code></pre>
118  *
119  * <p>See the docs for {@link Ext.data.BelongsToAssociation} and {@link Ext.data.HasManyAssociation} for details on the usage
120  * and configuration of associations. Note that associations can also be specified like this:</p>
121  *
122 <pre><code>
123 Ext.define('User', {
124     extend: 'Ext.data.Model',
125     fields: ['id'],
126
127     associations: [
128         {type: 'hasMany', model: 'Post',    name: 'posts'},
129         {type: 'hasMany', model: 'Comment', name: 'comments'}
130     ]
131 });
132 </code></pre>
133  *
134  * <p><u>Using a Proxy</u></p>
135  *
136  * <p>Models are great for representing types of data and relationships, but sooner or later we're going to want to
137  * load or save that data somewhere. All loading and saving of data is handled via a {@link Ext.data.proxy.Proxy Proxy},
138  * which can be set directly on the Model:</p>
139  *
140 <pre><code>
141 Ext.define('User', {
142     extend: 'Ext.data.Model',
143     fields: ['id', 'name', 'email'],
144
145     proxy: {
146         type: 'rest',
147         url : '/users'
148     }
149 });
150 </code></pre>
151  *
152  * <p>Here we've set up a {@link Ext.data.proxy.Rest Rest Proxy}, which knows how to load and save data to and from a
153  * RESTful backend. Let's see how this works:</p>
154  *
155 <pre><code>
156 var user = Ext.ModelManager.create({name: 'Ed Spencer', email: 'ed@sencha.com'}, 'User');
157
158 user.save(); //POST /users
159 </code></pre>
160  *
161  * <p>Calling {@link #save} on the new Model instance tells the configured RestProxy that we wish to persist this
162  * Model's data onto our server. RestProxy figures out that this Model hasn't been saved before because it doesn't
163  * have an id, and performs the appropriate action - in this case issuing a POST request to the url we configured
164  * (/users). We configure any Proxy on any Model and always follow this API - see {@link Ext.data.proxy.Proxy} for a full
165  * list.</p>
166  *
167  * <p>Loading data via the Proxy is equally easy:</p>
168  *
169 <pre><code>
170 //get a reference to the User model class
171 var User = Ext.ModelManager.getModel('User');
172
173 //Uses the configured RestProxy to make a GET request to /users/123
174 User.load(123, {
175     success: function(user) {
176         console.log(user.getId()); //logs 123
177     }
178 });
179 </code></pre>
180  *
181  * <p>Models can also be updated and destroyed easily:</p>
182  *
183 <pre><code>
184 //the user Model we loaded in the last snippet:
185 user.set('name', 'Edward Spencer');
186
187 //tells the Proxy to save the Model. In this case it will perform a PUT request to /users/123 as this Model already has an id
188 user.save({
189     success: function() {
190         console.log('The User was updated');
191     }
192 });
193
194 //tells the Proxy to destroy the Model. Performs a DELETE request to /users/123
195 user.destroy({
196     success: function() {
197         console.log('The User was destroyed!');
198     }
199 });
200 </code></pre>
201  *
202  * <p><u>Usage in Stores</u></p>
203  *
204  * <p>It is very common to want to load a set of Model instances to be displayed and manipulated in the UI. We do this
205  * by creating a {@link Ext.data.Store Store}:</p>
206  *
207 <pre><code>
208 var store = new Ext.data.Store({
209     model: 'User'
210 });
211
212 //uses the Proxy we set up on Model to load the Store data
213 store.load();
214 </code></pre>
215  *
216  * <p>A Store is just a collection of Model instances - usually loaded from a server somewhere. Store can also maintain
217  * a set of added, updated and removed Model instances to be synchronized with the server via the Proxy. See the
218  * {@link Ext.data.Store Store docs} for more information on Stores.</p>
219  *
220  * @constructor
221  * @param {Object} data An object containing keys corresponding to this model's fields, and their associated values
222  * @param {Number} id Optional unique ID to assign to this model instance
223  */
224 Ext.define('Ext.data.Model', {
225     alternateClassName: 'Ext.data.Record',
226     
227     mixins: {
228         observable: 'Ext.util.Observable'
229     },
230
231     requires: [
232         'Ext.ModelManager',
233         'Ext.data.Field',
234         'Ext.data.Errors',
235         'Ext.data.Operation',
236         'Ext.data.validations',
237         'Ext.data.proxy.Ajax',
238         'Ext.util.MixedCollection'
239     ],
240
241     onClassExtended: function(cls, data) {
242         var onBeforeClassCreated = data.onBeforeClassCreated;
243
244         data.onBeforeClassCreated = function(cls, data) {
245             var me = this,
246                 name = Ext.getClassName(cls),
247                 prototype = cls.prototype,
248                 superCls = cls.prototype.superclass,
249
250                 validations = data.validations || [],
251                 fields = data.fields || [],
252                 associations = data.associations || [],
253                 belongsTo = data.belongsTo,
254                 hasMany = data.hasMany,
255
256                 fieldsMixedCollection = new Ext.util.MixedCollection(false, function(field) {
257                     return field.name;
258                 }),
259
260                 associationsMixedCollection = new Ext.util.MixedCollection(false, function(association) {
261                     return association.name;
262                 }),
263
264                 superValidations = superCls.validations,
265                 superFields = superCls.fields,
266                 superAssociations = superCls.associations,
267
268                 association, i, ln,
269                 dependencies = [];
270
271             // Save modelName on class and its prototype
272             cls.modelName = name;
273             prototype.modelName = name;
274
275             // Merge the validations of the superclass and the new subclass
276             if (superValidations) {
277                 validations = superValidations.concat(validations);
278             }
279
280             data.validations = validations;
281
282             // Merge the fields of the superclass and the new subclass
283             if (superFields) {
284                 fields = superFields.items.concat(fields);
285             }
286
287             for (i = 0, ln = fields.length; i < ln; ++i) {
288                 fieldsMixedCollection.add(new Ext.data.Field(fields[i]));
289             }
290
291             data.fields = fieldsMixedCollection;
292
293             //associations can be specified in the more convenient format (e.g. not inside an 'associations' array).
294             //we support that here
295             if (belongsTo) {
296                 belongsTo = Ext.Array.from(belongsTo);
297
298                 for (i = 0, ln = belongsTo.length; i < ln; ++i) {
299                     association = belongsTo[i];
300
301                     if (!Ext.isObject(association)) {
302                         association = {model: association};
303                     }
304
305                     association.type = 'belongsTo';
306                     associations.push(association);
307                 }
308
309                 delete data.belongsTo;
310             }
311
312             if (hasMany) {
313                 hasMany = Ext.Array.from(hasMany);
314                 for (i = 0, ln = hasMany.length; i < ln; ++i) {
315                     association = hasMany[i];
316
317                     if (!Ext.isObject(association)) {
318                         association = {model: association};
319                     }
320
321                     association.type = 'hasMany';
322                     associations.push(association);
323                 }
324
325                 delete data.hasMany;
326             }
327
328             if (superAssociations) {
329                 associations = superAssociations.items.concat(associations);
330             }
331
332             for (i = 0, ln = associations.length; i < ln; ++i) {
333                 dependencies.push('association.' + associations[i].type.toLowerCase());
334             }
335
336             if (data.proxy) {
337                 if (typeof data.proxy === 'string') {
338                     dependencies.push('proxy.' + data.proxy);
339                 }
340                 else if (typeof data.proxy.type === 'string') {
341                     dependencies.push('proxy.' + data.proxy.type);
342                 }
343             }
344
345             Ext.require(dependencies, function() {
346                 Ext.ModelManager.registerType(name, cls);
347
348                 for (i = 0, ln = associations.length; i < ln; ++i) {
349                     association = associations[i];
350
351                     Ext.apply(association, {
352                         ownerModel: name,
353                         associatedModel: association.model
354                     });
355
356                     if (Ext.ModelManager.getModel(association.model) === undefined) {
357                         Ext.ModelManager.registerDeferredAssociation(association);
358                     } else {
359                         associationsMixedCollection.add(Ext.data.Association.create(association));
360                     }
361                 }
362
363                 data.associations = associationsMixedCollection;
364
365                 onBeforeClassCreated.call(me, cls, data);
366
367                 cls.setProxy(cls.prototype.proxy || cls.prototype.defaultProxyType);
368
369                 // Fire the onModelDefined template method on ModelManager
370                 Ext.ModelManager.onModelDefined(cls);
371             });
372         };
373     },
374
375     inheritableStatics: {
376         /**
377          * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext#createByAlias Ext.createByAlias}
378          * @param {String/Object/Ext.data.proxy.Proxy} proxy The proxy
379          * @static
380          */
381         setProxy: function(proxy) {
382             //make sure we have an Ext.data.proxy.Proxy object
383             if (!proxy.isProxy) {
384                 if (typeof proxy == "string") {
385                     proxy = {
386                         type: proxy
387                     };
388                 }
389                 proxy = Ext.createByAlias("proxy." + proxy.type, proxy);
390             }
391             proxy.setModel(this);
392             this.proxy = this.prototype.proxy = proxy;
393
394             return proxy;
395         },
396
397         /**
398          * Returns the configured Proxy for this Model
399          * @return {Ext.data.proxy.Proxy} The proxy
400          */
401         getProxy: function() {
402             return this.proxy;
403         },
404
405         /**
406          * <b>Static</b>. Asynchronously loads a model instance by id. Sample usage:
407     <pre><code>
408     MyApp.User = Ext.define('User', {
409         extend: 'Ext.data.Model',
410         fields: [
411             {name: 'id', type: 'int'},
412             {name: 'name', type: 'string'}
413         ]
414     });
415
416     MyApp.User.load(10, {
417         scope: this,
418         failure: function(record, operation) {
419             //do something if the load failed
420         },
421         success: function(record, operation) {
422             //do something if the load succeeded
423         },
424         callback: function(record, operation) {
425             //do something whether the load succeeded or failed
426         }
427     });
428     </code></pre>
429          * @param {Number} id The id of the model to load
430          * @param {Object} config Optional config object containing success, failure and callback functions, plus optional scope
431          * @member Ext.data.Model
432          * @method load
433          * @static
434          */
435         load: function(id, config) {
436             config = Ext.apply({}, config);
437             config = Ext.applyIf(config, {
438                 action: 'read',
439                 id    : id
440             });
441
442             var operation  = Ext.create('Ext.data.Operation', config),
443                 scope      = config.scope || this,
444                 record     = null,
445                 callback;
446
447             callback = function(operation) {
448                 if (operation.wasSuccessful()) {
449                     record = operation.getRecords()[0];
450                     Ext.callback(config.success, scope, [record, operation]);
451                 } else {
452                     Ext.callback(config.failure, scope, [record, operation]);
453                 }
454                 Ext.callback(config.callback, scope, [record, operation]);
455             };
456
457             this.proxy.read(operation, callback, this);
458         }
459     },
460
461     statics: {
462         PREFIX : 'ext-record',
463         AUTO_ID: 1,
464         EDIT   : 'edit',
465         REJECT : 'reject',
466         COMMIT : 'commit',
467
468         /**
469          * Generates a sequential id. This method is typically called when a record is {@link #create}d
470          * and {@link #Record no id has been specified}. The id will automatically be assigned
471          * to the record. The returned id takes the form:
472          * <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul>
473          * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.PREFIX</tt>
474          * (defaults to <tt>'ext-record'</tt>)</p></li>
475          * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.AUTO_ID</tt>
476          * (defaults to <tt>1</tt> initially)</p></li>
477          * </ul></div>
478          * @param {Ext.data.Model} rec The record being created.  The record does not exist, it's a {@link #phantom}.
479          * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
480          * @static
481          */
482         id: function(rec) {
483             var id = [this.PREFIX, '-', this.AUTO_ID++].join('');
484             rec.phantom = true;
485             rec.internalId = id;
486             return id;
487         }
488     },
489     
490     /**
491      * Internal flag used to track whether or not the model instance is currently being edited. Read-only
492      * @property editing
493      * @type Boolean
494      */
495     editing : false,
496
497     /**
498      * Readonly flag - true if this Record has been modified.
499      * @type Boolean
500      */
501     dirty : false,
502
503     /**
504      * @cfg {String} persistanceProperty The property on this Persistable object that its data is saved to.
505      * Defaults to 'data' (e.g. all persistable data resides in this.data.)
506      */
507     persistanceProperty: 'data',
508
509     evented: false,
510     isModel: true,
511
512     /**
513      * <tt>true</tt> when the record does not yet exist in a server-side database (see
514      * {@link #setDirty}).  Any record which has a real database pk set as its id property
515      * is NOT a phantom -- it's real.
516      * @property phantom
517      * @type {Boolean}
518      */
519     phantom : false,
520
521     /**
522      * @cfg {String} idProperty The name of the field treated as this Model's unique id (defaults to 'id').
523      */
524     idProperty: 'id',
525
526     /**
527      * The string type of the default Model Proxy. Defaults to 'ajax'
528      * @property defaultProxyType
529      * @type String
530      */
531     defaultProxyType: 'ajax',
532
533     /**
534      * An array of the fields defined on this model
535      * @property fields
536      * @type {Array}
537      */
538
539     // raw not documented intentionally, meant to be used internally.
540     constructor: function(data, id, raw) {
541         data = data || {};
542         
543         var me = this,
544             fields,
545             length,
546             field,
547             name,
548             i,
549             isArray = Ext.isArray(data),
550             newData = isArray ? {} : null; // to hold mapped array data if needed
551
552         /**
553          * An internal unique ID for each Model instance, used to identify Models that don't have an ID yet
554          * @property internalId
555          * @type String
556          * @private
557          */
558         me.internalId = (id || id === 0) ? id : Ext.data.Model.id(me);
559         
560         /**
561          * The raw data used to create this model if created via a reader.
562          * @property raw
563          * @type Object
564          */
565         me.raw = raw;
566
567         Ext.applyIf(me, {
568             data: {}    
569         });
570         
571         /**
572          * Key: value pairs of all fields whose values have changed
573          * @property modified
574          * @type Object
575          */
576         me.modified = {};
577
578         me[me.persistanceProperty] = {};
579
580         me.mixins.observable.constructor.call(me);
581
582         //add default field values if present
583         fields = me.fields.items;
584         length = fields.length;
585
586         for (i = 0; i < length; i++) {
587             field = fields[i];
588             name  = field.name;
589
590             if (isArray){ 
591                 // Have to map array data so the values get assigned to the named fields
592                 // rather than getting set as the field names with undefined values.
593                 newData[name] = data[i];
594             }
595             else if (data[name] === undefined) {
596                 data[name] = field.defaultValue;
597             }
598         }
599
600         me.set(newData || data);
601         // clear any dirty/modified since we're initializing
602         me.dirty = false;
603         me.modified = {};
604
605         if (me.getId()) {
606             me.phantom = false;
607         }
608
609         if (typeof me.init == 'function') {
610             me.init();
611         }
612
613         me.id = me.modelName + '-' + me.internalId;
614
615         Ext.ModelManager.register(me);
616     },
617     
618     /**
619      * Returns the value of the given field
620      * @param {String} fieldName The field to fetch the value for
621      * @return {Mixed} The value
622      */
623     get: function(field) {
624         return this[this.persistanceProperty][field];
625     },
626     
627     /**
628      * Sets the given field to the given value, marks the instance as dirty
629      * @param {String|Object} fieldName The field to set, or an object containing key/value pairs
630      * @param {Mixed} value The value to set
631      */
632     set: function(fieldName, value) {
633         var me = this,
634             fields = me.fields,
635             modified = me.modified,
636             convertFields = [],
637             field, key, i, currentValue;
638
639         /*
640          * If we're passed an object, iterate over that object. NOTE: we pull out fields with a convert function and
641          * set those last so that all other possible data is set before the convert function is called
642          */
643         if (arguments.length == 1 && Ext.isObject(fieldName)) {
644             for (key in fieldName) {
645                 if (fieldName.hasOwnProperty(key)) {
646                 
647                     //here we check for the custom convert function. Note that if a field doesn't have a convert function,
648                     //we default it to its type's convert function, so we have to check that here. This feels rather dirty.
649                     field = fields.get(key);
650                     if (field && field.convert !== field.type.convert) {
651                         convertFields.push(key);
652                         continue;
653                     }
654                     
655                     me.set(key, fieldName[key]);
656                 }
657             }
658
659             for (i = 0; i < convertFields.length; i++) {
660                 field = convertFields[i];
661                 me.set(field, fieldName[field]);
662             }
663
664         } else {
665             if (fields) {
666                 field = fields.get(fieldName);
667
668                 if (field && field.convert) {
669                     value = field.convert(value, me);
670                 }
671             }
672             currentValue = me.get(fieldName);
673             me[me.persistanceProperty][fieldName] = value;
674             
675             if (field && field.persist && !me.isEqual(currentValue, value)) {
676                 me.dirty = true;
677                 me.modified[fieldName] = currentValue;
678             }
679
680             if (!me.editing) {
681                 me.afterEdit();
682             }
683         }
684     },
685     
686     /**
687      * Checks if two values are equal, taking into account certain
688      * special factors, for example dates.
689      * @private
690      * @param {Object} a The first value
691      * @param {Object} b The second value
692      * @return {Boolean} True if the values are equal
693      */
694     isEqual: function(a, b){
695         if (Ext.isDate(a) && Ext.isDate(b)) {
696             return a.getTime() === b.getTime();
697         }
698         return a === b;
699     },
700     
701     /**
702      * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
703      * are relayed to the containing store. When an edit has begun, it must be followed
704      * by either {@link #endEdit} or {@link #cancelEdit}.
705      */
706     beginEdit : function(){
707         var me = this;
708         if (!me.editing) {
709             me.editing = true;
710             me.dirtySave = me.dirty;
711             me.dataSave = Ext.apply({}, me[me.persistanceProperty]);
712             me.modifiedSave = Ext.apply({}, me.modified);
713         }
714     },
715     
716     /**
717      * Cancels all changes made in the current edit operation.
718      */
719     cancelEdit : function(){
720         var me = this;
721         if (me.editing) {
722             me.editing = false;
723             // reset the modified state, nothing changed since the edit began
724             me.modified = me.modifiedSave;
725             me[me.persistanceProperty] = me.dataSave;
726             me.dirty = me.dirtySave;
727             delete me.modifiedSave;
728             delete me.dataSave;
729             delete me.dirtySave;
730         }
731     },
732     
733     /**
734      * End an edit. If any data was modified, the containing store is notified
735      * (ie, the store's <code>update</code> event will fire).
736      * @param {Boolean} silent True to not notify the store of the change
737      */
738     endEdit : function(silent){
739         var me = this;
740         if (me.editing) {
741             me.editing = false;
742             delete me.modifiedSave;
743             delete me.dataSave;
744             delete me.dirtySave;
745             if (silent !== true && me.dirty) {
746                 me.afterEdit();
747             }
748         }
749     },
750     
751     /**
752      * Gets a hash of only the fields that have been modified since this Model was created or commited.
753      * @return Object
754      */
755     getChanges : function(){
756         var modified = this.modified,
757             changes  = {},
758             field;
759
760         for (field in modified) {
761             if (modified.hasOwnProperty(field)){
762                 changes[field] = this.get(field);
763             }
764         }
765
766         return changes;
767     },
768     
769     /**
770      * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
771      * since the load or last commit.
772      * @param {String} fieldName {@link Ext.data.Field#name}
773      * @return {Boolean}
774      */
775     isModified : function(fieldName) {
776         return this.modified.hasOwnProperty(fieldName);
777     },
778     
779     /**
780      * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>.  This method
781      * is used interally when adding <code>{@link #phantom}</code> records to a
782      * {@link Ext.data.Store#writer writer enabled store}.</p>
783      * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
784      * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
785      * have a create action composed for it during {@link Ext.data.Store#save store save}
786      * operations.</p>
787      */
788     setDirty : function() {
789         var me = this,
790             name;
791         
792         me.dirty = true;
793
794         me.fields.each(function(field) {
795             if (field.persist) {
796                 name = field.name;
797                 me.modified[name] = me.get(name);
798             }
799         }, me);
800     },
801
802     //<debug>
803     markDirty : function() {
804         if (Ext.isDefined(Ext.global.console)) {
805             Ext.global.console.warn('Ext.data.Model: markDirty has been deprecated. Use setDirty instead.');
806         }
807         return this.setDirty.apply(this, arguments);
808     },
809     //</debug>
810     
811     /**
812      * Usually called by the {@link Ext.data.Store} to which this model instance has been {@link #join joined}.
813      * Rejects all changes made to the model instance since either creation, or the last commit operation.
814      * Modified fields are reverted to their original values.
815      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
816      * to have their code notified of reject operations.</p>
817      * @param {Boolean} silent (optional) True to skip notification of the owning
818      * store of the change (defaults to false)
819      */
820     reject : function(silent) {
821         var me = this,
822             modified = me.modified,
823             field;
824
825         for (field in modified) {
826             if (modified.hasOwnProperty(field)) {
827                 if (typeof modified[field] != "function") {
828                     me[me.persistanceProperty][field] = modified[field];
829                 }
830             }
831         }
832
833         me.dirty = false;
834         me.editing = false;
835         me.modified = {};
836
837         if (silent !== true) {
838             me.afterReject();
839         }
840     },
841
842     /**
843      * Usually called by the {@link Ext.data.Store} which owns the model instance.
844      * Commits all changes made to the instance since either creation or the last commit operation.
845      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
846      * to have their code notified of commit operations.</p>
847      * @param {Boolean} silent (optional) True to skip notification of the owning
848      * store of the change (defaults to false)
849      */
850     commit : function(silent) {
851         var me = this;
852         
853         me.dirty = false;
854         me.editing = false;
855
856         me.modified = {};
857
858         if (silent !== true) {
859             me.afterCommit();
860         }
861     },
862
863     /**
864      * Creates a copy (clone) of this Model instance.
865      * @param {String} id (optional) A new id, defaults to the id
866      * of the instance being copied. See <code>{@link #id}</code>.
867      * To generate a phantom instance with a new id use:<pre><code>
868 var rec = record.copy(); // clone the record
869 Ext.data.Model.id(rec); // automatically generate a unique sequential id
870      * </code></pre>
871      * @return {Record}
872      */
873     copy : function(newId) {
874         var me = this;
875         
876         return new me.self(Ext.apply({}, me[me.persistanceProperty]), newId || me.internalId);
877     },
878
879     /**
880      * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext#createByAlias Ext.createByAlias}
881      * @param {String/Object/Ext.data.proxy.Proxy} proxy The proxy
882      * @static
883      */
884     setProxy: function(proxy) {
885         //make sure we have an Ext.data.proxy.Proxy object
886         if (!proxy.isProxy) {
887             if (typeof proxy === "string") {
888                 proxy = {
889                     type: proxy
890                 };
891             }
892             proxy = Ext.createByAlias("proxy." + proxy.type, proxy);
893         }
894         proxy.setModel(this.self);
895         this.proxy = proxy;
896
897         return proxy;
898     },
899
900     /**
901      * Returns the configured Proxy for this Model
902      * @return {Ext.data.proxy.Proxy} The proxy
903      */
904     getProxy: function() {
905         return this.proxy;
906     },
907
908     /**
909      * Validates the current data against all of its configured {@link #validations} and returns an
910      * {@link Ext.data.Errors Errors} object
911      * @return {Ext.data.Errors} The errors object
912      */
913     validate: function() {
914         var errors      = Ext.create('Ext.data.Errors'),
915             validations = this.validations,
916             validators  = Ext.data.validations,
917             length, validation, field, valid, type, i;
918
919         if (validations) {
920             length = validations.length;
921
922             for (i = 0; i < length; i++) {
923                 validation = validations[i];
924                 field = validation.field || validation.name;
925                 type  = validation.type;
926                 valid = validators[type](validation, this.get(field));
927
928                 if (!valid) {
929                     errors.add({
930                         field  : field,
931                         message: validation.message || validators[type + 'Message']
932                     });
933                 }
934             }
935         }
936
937         return errors;
938     },
939
940     /**
941      * Checks if the model is valid. See {@link #validate}.
942      * @return {Boolean} True if the model is valid.
943      */
944     isValid: function(){
945         return this.validate().isValid();
946     },
947
948     /**
949      * Saves the model instance using the configured proxy
950      * @param {Object} options Options to pass to the proxy
951      * @return {Ext.data.Model} The Model instance
952      */
953     save: function(options) {
954         options = Ext.apply({}, options);
955
956         var me     = this,
957             action = me.phantom ? 'create' : 'update',
958             record = null,
959             scope  = options.scope || me,
960             operation,
961             callback;
962
963         Ext.apply(options, {
964             records: [me],
965             action : action
966         });
967
968         operation = Ext.create('Ext.data.Operation', options);
969
970         callback = function(operation) {
971             if (operation.wasSuccessful()) {
972                 record = operation.getRecords()[0];
973                 //we need to make sure we've set the updated data here. Ideally this will be redundant once the
974                 //ModelCache is in place
975                 me.set(record.data);
976                 record.dirty = false;
977
978                 Ext.callback(options.success, scope, [record, operation]);
979             } else {
980                 Ext.callback(options.failure, scope, [record, operation]);
981             }
982
983             Ext.callback(options.callback, scope, [record, operation]);
984         };
985
986         me.getProxy()[action](operation, callback, me);
987
988         return me;
989     },
990
991     /**
992      * Destroys the model using the configured proxy
993      * @param {Object} options Options to pass to the proxy
994      * @return {Ext.data.Model} The Model instance
995      */
996     destroy: function(options){
997         options = Ext.apply({}, options);
998
999         var me     = this,
1000             record = null,
1001             scope  = options.scope || me,
1002             operation,
1003             callback;
1004
1005         Ext.apply(options, {
1006             records: [me],
1007             action : 'destroy'
1008         });
1009
1010         operation = Ext.create('Ext.data.Operation', options);
1011         callback = function(operation) {
1012             if (operation.wasSuccessful()) {
1013                 Ext.callback(options.success, scope, [record, operation]);
1014             } else {
1015                 Ext.callback(options.failure, scope, [record, operation]);
1016             }
1017             Ext.callback(options.callback, scope, [record, operation]);
1018         };
1019
1020         me.getProxy().destroy(operation, callback, me);
1021         return me;
1022     },
1023
1024     /**
1025      * Returns the unique ID allocated to this model instance as defined by {@link #idProperty}
1026      * @return {Number} The id
1027      */
1028     getId: function() {
1029         return this.get(this.idProperty);
1030     },
1031
1032     /**
1033      * Sets the model instance's id field to the given id
1034      * @param {Number} id The new id
1035      */
1036     setId: function(id) {
1037         this.set(this.idProperty, id);
1038     },
1039
1040     /**
1041      * Tells this model instance that it has been added to a store
1042      * @param {Ext.data.Store} store The store that the model has been added to
1043      */
1044     join : function(store) {
1045         /**
1046          * The {@link Ext.data.Store} to which this Record belongs.
1047          * @property store
1048          * @type {Ext.data.Store}
1049          */
1050         this.store = store;
1051     },
1052
1053     /**
1054      * Tells this model instance that it has been removed from the store
1055      */
1056     unjoin: function() {
1057         delete this.store;
1058     },
1059
1060     /**
1061      * @private
1062      * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
1063      * afterEdit method is called
1064      */
1065     afterEdit : function() {
1066         this.callStore('afterEdit');
1067     },
1068
1069     /**
1070      * @private
1071      * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
1072      * afterReject method is called
1073      */
1074     afterReject : function() {
1075         this.callStore("afterReject");
1076     },
1077
1078     /**
1079      * @private
1080      * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
1081      * afterCommit method is called
1082      */
1083     afterCommit: function() {
1084         this.callStore('afterCommit');
1085     },
1086
1087     /**
1088      * @private
1089      * Helper function used by afterEdit, afterReject and afterCommit. Calls the given method on the
1090      * {@link Ext.data.Store store} that this instance has {@link #join joined}, if any. The store function
1091      * will always be called with the model instance as its single argument.
1092      * @param {String} fn The function to call on the store
1093      */
1094     callStore: function(fn) {
1095         var store = this.store;
1096
1097         if (store !== undefined && typeof store[fn] == "function") {
1098             store[fn](this);
1099         }
1100     },
1101
1102     /**
1103      * Gets all of the data from this Models *loaded* associations.
1104      * It does this recursively - for example if we have a User which
1105      * hasMany Orders, and each Order hasMany OrderItems, it will return an object like this:
1106      * {
1107      *     orders: [
1108      *         {
1109      *             id: 123,
1110      *             status: 'shipped',
1111      *             orderItems: [
1112      *                 ...
1113      *             ]
1114      *         }
1115      *     ]
1116      * }
1117      * @return {Object} The nested data set for the Model's loaded associations
1118      */
1119     getAssociatedData: function(){
1120         return this.prepareAssociatedData(this, [], null);
1121     },
1122
1123     /**
1124      * @private
1125      * This complex-looking method takes a given Model instance and returns an object containing all data from
1126      * all of that Model's *loaded* associations. See (@link #getAssociatedData}
1127      * @param {Ext.data.Model} record The Model instance
1128      * @param {Array} ids PRIVATE. The set of Model instance internalIds that have already been loaded
1129      * @param {String} associationType (optional) The name of the type of association to limit to.
1130      * @return {Object} The nested data set for the Model's loaded associations
1131      */
1132     prepareAssociatedData: function(record, ids, associationType) {
1133         //we keep track of all of the internalIds of the models that we have loaded so far in here
1134         var associations     = record.associations.items,
1135             associationCount = associations.length,
1136             associationData  = {},
1137             associatedStore, associatedName, associatedRecords, associatedRecord,
1138             associatedRecordCount, association, id, i, j, type, allow;
1139
1140         for (i = 0; i < associationCount; i++) {
1141             association = associations[i];
1142             type = association.type;
1143             allow = true;
1144             if (associationType) {
1145                 allow = type == associationType;
1146             }
1147             if (allow && type == 'hasMany') {
1148
1149                 //this is the hasMany store filled with the associated data
1150                 associatedStore = record[association.storeName];
1151
1152                 //we will use this to contain each associated record's data
1153                 associationData[association.name] = [];
1154
1155                 //if it's loaded, put it into the association data
1156                 if (associatedStore && associatedStore.data.length > 0) {
1157                     associatedRecords = associatedStore.data.items;
1158                     associatedRecordCount = associatedRecords.length;
1159
1160                     //now we're finally iterating over the records in the association. We do this recursively
1161                     for (j = 0; j < associatedRecordCount; j++) {
1162                         associatedRecord = associatedRecords[j];
1163                         // Use the id, since it is prefixed with the model name, guaranteed to be unique
1164                         id = associatedRecord.id;
1165
1166                         //when we load the associations for a specific model instance we add it to the set of loaded ids so that
1167                         //we don't load it twice. If we don't do this, we can fall into endless recursive loading failures.
1168                         if (Ext.Array.indexOf(ids, id) == -1) {
1169                             ids.push(id);
1170
1171                             associationData[association.name][j] = associatedRecord.data;
1172                             Ext.apply(associationData[association.name][j], this.prepareAssociatedData(associatedRecord, ids, type));
1173                         }
1174                     }
1175                 }
1176             } else if (allow && type == 'belongsTo') {
1177                 associatedRecord = record[association.instanceName];
1178                 if (associatedRecord !== undefined) {
1179                     id = associatedRecord.id;
1180                     if (Ext.Array.indexOf(ids, id) == -1) {
1181                         ids.push(id);
1182                         associationData[association.name] = associatedRecord.data;
1183                         Ext.apply(associationData[association.name], this.prepareAssociatedData(associatedRecord, ids, type));
1184                     }
1185                 }
1186             }
1187         }
1188
1189         return associationData;
1190     }
1191 });