Search code examples
ember.jsember-cliember-routerember-controllers

Ember passing a model to transitionToRoute


I'm using Ember-cli with ember 1.11

I'm trying to use the transitionToRoute method in a controller to transition to a route and feed it a dynamically generated object as the model.

Here's my controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {      
      launch_scanner: function(){
        console.log('launch_scanner');
        var model = {name: "Edward", phone: "123", email: "[email protected]"};
        //the final app will pull the model variable from a QR scanner

        this.transitionToRoute('addcontact', model);
     }
  }      
});

When I trigger this action, the transitionToRoute method causes this error:

Uncaught Error: More context objects were passed than there are dynamic segments for the route: addcontact

If I leave out the model parameter, it transitions to the addcontact route just fine. What am I doing wrong?

Here is my router file:

import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('home', {path: '/'});
  this.resource('addcontact', {path: '/addcontact'});
});

export default Router;

Solution

  • You are dealing with a classic problem occurring in many Ember applications which is how to handle "new"/"create" situations.

    You cannot define a route such as

    this.route('addcontact', { path: /addcontact/:thing_id }
    

    because the the new contact doesn't have an id, and won't until it is persisted to the server, at which point it won't be new any more.

    Yet there is some point in your application, in your case I suppose on the "home" page, where the user pressed a "New Contact" button, and it may have useful information about what to create or how to create it, and might even want to create the object right there using this.store.createRecord--yet how does one pass that information, or the new record, to the addcontacdt route, which can have no dynamic segment?

    Some ideas include:

    1. Create the new contact in your home route or whatever, and store it in the controller. Then, in the model hook of the new route, retrieve it using this.controllerFor('home').get('newContact').

    2. Pass necessary parameters for creating the new object, if any, to the addcontact route as query parameters, using transitionTo('newcontact', queryParameters). Then, in the model hook, create the new object using this.store.createRecord('contact', transition.queryParameters) or something equivalent.