Upgrade to ExtJS 4.0.7 - Released 10/19/2011
[extjs.git] / docs / guides / forms / examples / model_binding / app.js
1 /**
2  * @example Binding a Model to a Form
3  *
4  */
5 Ext.require('Ext.form.Panel');
6 Ext.require('Ext.form.field.Date');
7
8 Ext.define('User', {
9     extend: 'Ext.data.Model',
10     fields: ['firstName', 'lastName', 'birthDate'],
11     proxy: {
12         type: 'ajax',
13         api: {
14             read: 'data/get_user',
15             update: 'data/update_user'
16         },
17         reader: {
18             type: 'json',
19             root: 'users'
20         }
21     }
22 });
23
24 Ext.onReady(function() {
25
26     var userForm = Ext.create('Ext.form.Panel', {
27         renderTo: Ext.getBody(),
28         title: 'User Form',
29         height: 150,
30         width: 280,
31         bodyPadding: 10,
32         defaultType: 'textfield',
33         items: [
34             {
35                 fieldLabel: 'First Name',
36                 name: 'firstName'
37             },
38             {
39                 fieldLabel: 'Last Name',
40                 name: 'lastName'
41             },
42             {
43                 xtype: 'datefield',
44                 fieldLabel: 'Date of Birth',
45                 name: 'birthDate'
46             }
47         ],
48         buttons: [
49             {
50                 text: 'Submit',
51                 handler: function() {
52                     var form = this.up('form').getForm(), // get the basic form
53                         record = form.getRecord(); // get the underlying model instance
54                     if (form.isValid()) { // make sure the form contains valid data before submitting
55                         form.updateRecord(record); // update the record with the form data
56                         record.save({ // save the record to the server
57                             success: function(user) {
58                                 Ext.Msg.alert('Success', 'User saved successfully.')
59                             },
60                             failure: function(user) {
61                                 Ext.Msg.alert('Failure', 'Failed to save user.')
62                             }
63                         });
64                     } else { // display error alert if the data is invalid
65                         Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
66                     }
67                 }
68             }
69         ]
70     });
71
72     Ext.ModelMgr.getModel('User').load(1, { // load user with ID of "1"
73         success: function(user) {
74             userForm.loadRecord(user); // when user is loaded successfully, load the data into the form
75         }
76     });
77
78
79 });