Daniel Sh.
Daniel Sh.

Reputation: 2074

Create new item in Ember

im playing with the ember starter kit bloggr just to get familiarized with its stuff.

Jsbin

In the Posts section I want to be able to create a new post. This is the relevant changes according to the original code.

App.PostsRoute = Ember.Route.extend({  model: function() {
return posts;  },  
events: {
  createPost: function(){
    var posts = this.modelFor('posts');
    var post = posts.pushObject({
      id: posts.length
    });
    this.transitionTo('/edit', post);
  }    
}});

and the event gets fired when

 <tr><th><a href="#" {{action createPost}}>New Post</a></th></tr>
 <tr><th>Recent Posts</th></tr>

If you try to create a new post, there's clearly a new instance of posts (0 and 1 are hardcoded so you get post id=2) but the edit template is not rendered. The only way to get to do something is to first load post 0 or 1 and then click on the new one (just visible by "by") and edit it.

What I'd like to achieve is to get a fresh new edit instance of the template so I can set the fields for the newly created post.

Any suggestion?

Upvotes: 0

Views: 133

Answers (1)

kiwiupover
kiwiupover

Reputation: 1780

G'day Daniel

Here you go this jsbin is working.

To get this working I added Ember Data and the fixture adapter

App.ApplicationAdapter = DS.FixtureAdapter;

Then I turned the post object that came with the example into fixture data.

App.Post.FIXTURES = [{
 title: "Rails is Omakase"
}, { 
 title: "The Parley Letter"
}];

Next I adding a new posts route.

App.Router.map(function() {
 this.resource('about');
 this.resource('posts', function() {
   this.route('new');
   this.resource('post', { path: ':post_id' });
 });
});

Then added a link-to to that new route.

{{#link-to 'posts.new'}}New Post{{/link-to}}

In the PostsNewRoute model hook I creat a 'post'. The template uses the {{partial 'post/edit'}} to reuse the edit form.

Here is the PostsNewRoute code showing the save action.

 App.PostsNewRoute = Ember.Route.extend({
    model: function() {
      return this.get('store').createRecord('post');
    },
    actions: {
      save: function() {
        this.modelFor('postsNew').save();
        this.transitionTo('posts.index');
      }
    }
  });

If you have any more questions let me know.

Cheers

Upvotes: 2

Related Questions