app.js 2.4 KB

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