I am wondering why i am getting an empty instance each time i try to save a newly created record and it fails. I see like an empty record being added in my posts object only when i display errors. Also i tried sorting posts which let me see the top recent created posts but the behavior is kinda odd, because as soon as the post is created, it shows at the end and then immediately goes to the top. I am wondering if this is normal or maybe there is a way to wait for the server response and push the record with some sort of fade in effect, etc. Thanks.
index.hbs
<form {{action "savePost" post on="submit"}}>
<div class="form-group {{if errors.error-content "has-error has-feedback"}}">
{{textarea value=post
rows=3
placeholder="What are you thinking?"
id="content"
class="form-control"}}
<small class="help-block text-danger">
{{errors.error-content}}
</small>
</div>
<div class="clearfix">
<div class="pull-right">
<button type="submit"
class="btn btn-sm btn-success">
Create new post
</button>
</div>
</div>
</form>
{{#each sortedPosts as |post|}}
<article class="wrapper">
<p>{{post.content}}</p>
</article>
{{else}}
<article class="wrapper">
<p>NO CURRENT POSTS TO SHOW!</p>
</article>
{{/each}}
post.js
export default DS.Model.extend({
content: DS.attr('string'),
created_at: DS.attr('date')
});
index.js route
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
return this.store.findAll('post');
},
actions: {
savePost(content) {
const newPost = this.store.createRecord('post', {
content: content
});
newPost.save().then(() => {
this.controller.set('post', '');
this.controller.set('errors', []);
}).catch((resp) => {
let errors = {};
resp.errors.forEach((error) => {
errors[`error-${error.field}`] = error.messages[0];
});
this.controller.set('errors', errors);
});
},
willTransition() {
this.controller.get('post').rollbackAttributes();
this.controller.set('errors', []);
}
}
});
index.js controller
export default Ember.Controller.extend({
sortProp: ['created_at:desc'],
sortedPosts: Ember.computed.sort('model', 'sortProp')
});
Aucun commentaire:
Enregistrer un commentaire