2 * @example Associations and Validations
4 * This example demonstrates associations and validations on a {@link Ext.data.Model}.
5 * See console for output.
8 // define the User model
10 extend: 'Ext.data.Model',
11 fields: ['id', 'name', 'age', 'gender'],
13 {type: 'presence', name: 'name'},
14 {type: 'length', name: 'name', min: 5},
15 {type: 'format', name: 'age', matcher: /\d+/},
16 {type: 'inclusion', name: 'gender', list: ['male', 'female']},
17 {type: 'exclusion', name: 'name', list: ['admin']}
29 hasMany: 'Post' // shorthand for {model: 'Post', name: 'posts'}
32 //define the Post model
34 extend: 'Ext.data.Model',
35 fields: ['id', 'user_id', 'title', 'body'],
46 hasMany: {model: 'Comment', name: 'comments'}
49 //define the Comment model
50 Ext.define('Comment', {
51 extend: 'Ext.data.Model',
52 fields: ['id', 'post_id', 'name', 'message'],
57 Ext.require('Ext.data.Store');
58 Ext.onReady(function() {
59 // Loads User with ID 1 and related posts and comments using User's Proxy
61 success: function(user) {
62 console.log("User: " + user.get('name'));
64 // loop through the user's posts and print out the comments
65 user.posts().each(function(post) {
66 console.log("Comments for post: " + post.get('title'));
68 post.comments().each(function(comment) {
69 console.log(comment.get('message'));
72 // get the user reference from the post's belongsTo association
73 post.getUser(function(user) {
74 console.log('Just got the user reference from the post: ' + user.get('name'))
77 // try to change the post's user
79 callback: function(product, operation) {
80 if (operation.wasSuccessful()) {
81 console.log('Post\'s user was updated');
83 console.log('Post\'s user could not be updated');
92 title: 'Ext JS 4.0 MVC Architecture',
93 body: 'It\'s a great Idea to structure your Ext JS Applications using the built in MVC Architecture...'
102 // now lets try to create a new user with as many validation errors as we can
103 var newUser = Ext.create('User', {
106 gender: 'not a valid gender'
109 // run some validation on the new user we just created
110 var errors = newUser.validate();
112 console.log('Is User valid?', errors.isValid()); //returns 'false' as there were validation errors
113 console.log('All Errors:', errors.items); //returns the array of all errors found on this model instance
115 console.log('Age Errors:', errors.getByField('age')); //returns the errors for the age field