ember post

Very glad to have writtten the 5th chapter of "Love in the Afternoon With Ember Date", err wait...

Add The Form

The POST method to /dvds needs to be adjusted to create a new DVD using based on form data instead of a static Python dictionary.

First, let's add a form partial to index.html to create new DVDs:

    <script type="text/x-handlebars" id="dvd/_new">
    <p>
      <label for="new-title">Title</label>
      {{input type="text" id="new-title" value=model.title}}
    </p>
    <p>
      <label for="new-created_by">Created By:</label>
      {{input type="text" id="new-created_by" value=model.created_by}}
    </p>
    <p>
      <label for="new-rating">Rating:</label>
      {{input type="text" id="new-rating" value=model.rating}}
    </p>
    <p>
      <label for="new-file_url">File URL:</label>
      {{input type="text" id="new-file_url" value=model.file_url}}
    </p>
    <p>
      <button {{action 'new'}}>Add DVD</button>
    </p>
    <br/>
  </script>

Inside the index tempalate add a call the new partial at the top:

      {{partial "dvd/_new"}}

Create The New Action

In static/js/app.js create the IndexController and add an actions object with a new function:

  App.IndexController = Ember.ArrayController.extend({
  actions: {
    new: function() {
      console.log('creating new DVD...');

      var model = this.get('model');

      dvd = this.get('store').createRecord('dvd', {
        title: model.get('title'),
        created_by: model.get('created_by'),
        rating: model.get('rating'),
        file_url: model.get('file_url'),
      });
      dvd.save().then(function(data) {
        // Clear the form.
        $(':input').val('');
      });
    },
  }
});

Refresh http://localhost:5000, or browse to it if it's not open, and when you click the "Add DVD" button you should see a HTTP POST to /dvds via XHR in your JavaScript console.

At the moment this will create yet another entry for the fantastic movie Super Bad, but we'll change that shortly.

Update The Server POST Action

Next, in server.py change the code inside the if (request.method == 'POST') to:

      # Add new object.
    new_dvd = json.loads(request.data)
    dvd = Dvd()

    # Set the SQLAlchemy object's attributes.
    for key, value in new_dvd['dvd'].iteritems():
      setattr(dvd, key, value)

    session.add(dvd)
    session.commit()

    return json.dumps(True)

This will create a new Dvd object based on the JSON data sent via POST by Ember Data.

Refresh the page, and after filling in the form and clicking the "Add DVD" button you should see a new entry at the bottom of the list. The id field should be blank because we didn't return the new id from the server. If you refresh the page the new entry will have an id matching the database entry.

Hurray, we can now create new entries in our table.