How to show error messages in template after becameInvalid method
ember-data, ember.js
Solution
I figured it out:
setup
- Ember 1.2.0
- Ember Data 1.0.0-beta.4+canary.7af6fcb0
- Handlebars 1.1.2 runtime
model
Docket.Customer = DS.Model.extend({
name: DS.attr('string'),
initial: DS.attr('string'),
description: DS.attr('string'),
number: DS.attr('string'),
archived: DS.attr('boolean')
});
controller
var _this = this;
// Create new record
var customer = this.store.createRecord('customer', data);
// Check for server errors (422) when saving
customer.save().then(function(){
_this.resetAndCloseForm(form);
}, function(response){
_this.set('errors',response.errors);
});
route
model: function() {
this.store.find('customer');
return this.store.filter('customer', function(customer) {
// prevent Ember to insert new elements to the DOM if they are invalid
// .get('isValid') returns always true, I think this is a bug, so I'm checking the ID
return customer.get('id')
})
}
template
{{#if errors}}{{errors.name}}{{/if}}
Problem
I'm using Ember.js to display a list of customers. Inside this template, I have a modal to create new customers. Now, when creating invalid customers (e.g. duplicate name), the errors should be shown in the template. How can I get this to work? model ``` Docket.Customer = DS.Model.extend({ name: DS.attr('string'), initial: DS.attr('string'), description: DS.attr('string'), errors: {}, becameInvalid: function(errors) { this.set('errors', errors.get('errors')); console.log(this.get('errors')); } }); ``` console output template ``` <h1>Customers<button data-uk-modal="{target:'#customer-modal'}" class="icon-plus">New customer</button></h1> <div id="customer-modal" class="uk-modal"> <div class="uk-modal-dialog uk-modal-dialog-slide"> <a class="uk-modal-close uk-close"></a> <form class="uk-form" {{action "save" on="submit"}}> <fieldset> <legend>New customer</legend> <div class="uk-form-row"> {{view Ember.TextField valueBinding="name" name="name" class="uk-width-1-1" placeholder="Name" required="" }} {{#if errors}}foo{{/if}} {{#if errors.name}}{{errors.name}}{{/if}} </div> <div class="uk-form-row"> {{view Ember.TextField valueBinding="initial" name="initial" class="uk-width-1-1" placeholder="Initial" required="" }} </div> <div class="uk-form-row"> {{view Ember.TextArea valueBinding="description" name="description" class="uk-width-1-1" placeholder="Description"}} </div> <div class="uk-form-row"> <button type="submit" class="icon-check">Save</button> </div> </fieldset> </form> </div> </div> <ul class="entries"> {{#each}} <li> <div class="actions"> <button {{action "remove" id}} class="icon-close"></button> </div> <div class="link" {{action "edit" id}} data-uk-modal="{target:'#customer-modal'}"> <span class="initial">{{initial}}</span>{{name}} </div> </li> {{else}} <li>No customers</li> {{/each}} </ul> ```