Ember - v1.7.0
Ember Data - v1.0.0-beta.10
I created a modal component using zurb foundation 5 CSS framework reveal features, though all works well, am unable to save data captured from the form in controller save action.
Controller which handles on save button execution
App.PersonModalController = Ember.ObjectController.extend({
actions: {
close: function() {
return this.send( 'closeModal' );
},
save:function() {
this.get('model').save();
}
}
});
The issue am facing is that the this.get('model').save() is not working and data is not been posted to restful backend.
Am not sure exactly how to go about storing the data captured from the form, when I console.log( this.get('model') ); it appears to be a proper model object with all the bells and whistles.
I tried obtaining the store to add model to it but that doesn't work too.
A. Addendum
After searching around I came across a number of Stack Overflow questions relating to this.get('model').save() it appears it doesn't quite work as expect, perhaps based on context.
difference-between-model-save-versus-model-getstore-commit
ember-js-how-to-save-a-model
save-record-of-model-is-not-working-in-ember-data-1-0-0-beta-3
When I change code to the following:
App.PersonModalController = Ember.ObjectController.extend({
actions: {
close: function() {
return this.send( 'closeModal' );
},
save:function() {
var person = this.store.createRecord('person',{firstName:firstName,lastName:lastName});
person.save();
}
}
});
It POSTs data correctly to back-end and saves, I however believe there must be a better way, cause if you have a form with say 50 fields, you won't want to manually set each attribute.
After careful inspection, though posting occurs, the data posted is empty.
I would try to continue your save method as in Bart's answer to the ember-js-how-to-save-a-model question.
person.save().then(function() {
// SUCCESS
}, function() {
// FAILURE
});
and in those methods I would console.log() the results.
I would imagine it has something to do with the promise aspect of the save functionality.
Related
I'm currently using EmberJs along with Ember-Data to build an app backed by a Laravel JSON api.
I got a little issue on the saving process, mostly on model creation.
Here is my workflow :
The Ember ObjectController saves itself this.get("model").save()
Laravel (REST api) receives the data and persist it, therefore
creating a unique ID for it
The api return the new data (that
respect Ember convention) with the proper ID
???? Ember-Data doesn't
seems to care about the response since it does nothing...
The problem here : the id remains undefined even if it has been given...
The workaround I found is to reload models... but it's a big performance flaw considering that the data I want to be reloaded it available to Ember straight after the save()
any ideas ?
EDIT **
The problem only occurs on the first object that I add. When I repeat the process the next objects are refreshed correctly. If I hit refresh, it start again : the first object miss his refresh and the following are okay.
Here my code about the add process :
route
App.CategoriesNewRoute = Ember.Route.extend({
model: function()
{
return this.store.createRecord("category").set("active", true);
},
setupController: function(ctrl, model)
{
ctrl.set("errors", 0);
ctrl.set("model", model);
}
});
I don't have any Router for CategoriesRoute since the data is all in my ArrayController from the start.
controller
App.CategoriesNewController = Ember.ObjectController.extend({
needs: "application",
actions:
{
save: function()
{
this.get("model").save();
this.get("target").transitionTo("categories");
},
cancel: function()
{
this.get("model").rollback();
this.get("target").transitionTo("categories");
}
}
});
EDIT ** 2
I tried the code provided below with no success...
I added 2 records, and the first don't have it's ID... the second got it, so the problem appears to only be on the first save...
Here are the 2 responses I got from my API
ObjectA
{"category":{"nameFr":"aaa","nameEn":"aaa","active":true,"id":10}}
ObjectB
{"category":{"nameFr":"bbb","nameEn":"bbb","active":true,"id":11}}
It could be because you're transitioning before the save finishes, and so the model hook on the categories route fires while the model you're saving is still in flight (are you getting any errors in the console?). Try changing the save action to
save: function()
{
var that = this;
this.get("model").save().then(function(){
that.get("target").transitionTo("categories");
});
},
Also, you don't need to this.get('target')... as there's a controller method transitionToRoute. You can simplify to:
save: function()
{
var that = this;
this.get("model").save().then(function(){
that.transitionToRoute("categories");
});
},
Found that the problem seems to be on Ember-Data's side...
documented the whole thing here :
http://discuss.emberjs.com/t/missing-id-on-first-save-on-a-new-object/4752
I am testing my application, so I am doing the following:
I show an index view (#/locators/index), of Locator objects, which I initially load with App.Locator.find();
I modify the backend manually
Manually (with a button/action) I trigger a refresh of the data in the ember frontend, without changing the route. I do this with App.Locator.find().then(function(recordArray) {recordArray.update();});. I see via console logging that a list request is sent to the backend, and that the up-to-date data is received. I assume this is used to update the store.
BUT: The view does not update itself to show this new data
Why does the view not get automatically updated when the store receives new data? Isn't that the whole point of the data binding in Ember?
If I now do the following:
Open any other route
Go back to the locators index route (#/locators/index)
Ember sends a new request to list the locators
The index view is shown, with the correct data (since it was already in the store?)
New data is received
(I am not 100% sure that 4 and 5 happen in that order, but I am quite certain)
So, my impression is that the data is properly updated in the store, but that somehow a full re-rendering of the view is needed to display this new data, for example by leaving and re-entering the route. Is this true? Can I force this re-rendering programmatically?
Ember changes view data when the underlying model is changed by the controller(Which is binded to the view)
(Only when the state of the application changes(url changes) router hooks are called)
Your problem could be solved when you do this.refesh() inside your route by capturing the action triggered by your view.
App.IndexRoute = Ember.Route.extend({
actions: {
dataChanged: function() {
this.refresh();
}
},
//rest of your code goes here
});
for this to work your handlebar template which modifies the data shoud have an action called dataChanged
example :
Assume this action is responsible for changing/modifying/deleting the underlying data
<button {{action 'dataChanged'}}> Change Data </button>
Refresh method actually does a model refresh and passes it to the corresponding controller which indeed changes the view.
There a couple of things that come to mind you could try:
If you are inside of an ArrayController force the content to be replaced with the new data:
this.replaceContent(0, recordArray.get('length'), recordArray);
Or try to call reload on every single record trough looping the recordArray:
App.Locator.find().then(function(recordArray) {
recordArray.forEach(function(index, record) {
record.reload();
}
}
And if the second approach works, you could also override the didLoad hook in your model class without having to loop over them one by one:
App.Locator = DS.Model.extend({
...
didLoad: function(){
this.reload();
}
});
If this works and you need this behaviour in more model classes consider creating a general mixin to use in more model classes:
App.AutoReloadMixin = Ember.Mixin.create({
didLoad: function() {
this._super();
this.reload();
}
});
App.Locator = DS.Model.extend(App.AutoReloadMixin, {
...
});
App.Phone = DS.Model.extend(App.AutoReloadMixin, {
...
});
Update in response to your answer
Handlebars.registerHelper is not binding aware, I'm sure this was causing your binding not to fire. You should have used Handlebars.registerBoundHelper or simply Handlebars.helper which is equivalent:
Handlebars.helper('grayOutIfUndef', function(property, txt_if_not_def) {
...
});
Hope this helps.
Somehow this seems to be due to the fact that I am using custom handlebar helpers, like the following:
Handlebars.registerHelper('grayOutIfUndef', function(property, txt_if_not_def) {
// HANDLEBARS passes a context object in txt_if_not_def if we do not give a default value
if (typeof txt_if_not_def !== 'string') { txt_if_not_def = DEFAULT_UNDEFINED_STR; }
// If property is not defined, we return the grayed out txt_if_not_def
var value = Ember.Handlebars.get(this, property);
if (!value) { value = App.grayOut(txt_if_not_def); }
return new Handlebars.SafeString(value);
});
Which I have been using like this:
{{grayOutIfUndef formattedStartnode}
Now I have moved to a view:
{{view App.NodeIconView nodeIdBinding="outputs.startnode"}}
Which is implemented like this:
App.NodeIconView = Ember.View.extend({
render: function(buffer) {
var nodeId = this.get('nodeId'), node, html;
if (nodeId) {
node = App.getNode(nodeId);
}
if (node) {
html = App.formattedLabel.call(node, true);
} else {
html = App.grayOut(UNDEFINED_NODE_NAME);
}
return buffer.push(html);
}
});
I am not sure why, but it seems the use of the custom handlebars helper breaks the property binding mechanism (maybe my implementation was wrong)
UPDATE:
THIS IS A NON-ISSUE
(see below)
So I wrote a jsfiddle to show the bad behavior except the fiddle works! and my real code doesn't. The only difference is I am using the RESTAdapter in my real code so the data is pulled from server instead of FIXTURES.
In the jsfiddle: first click 'Simulate 1st manual load', then click the 2nd button to see it work properly (i.e. loading new or updated data to the store multiple times in a row)
http://jsfiddle.net/iceking1624/NZZ42/4/
The Issue
I am sending updated information over websockets to my Ember App. I successfully set up a listener to trigger a function on the correct controller and am able to update records the first time. But all successive attempts do not update the store and I wonder if this has to do with the state of the store? But I am unsure of how to handle if that is the case.
This is the code that updates or adds the records that come over websockets:
App.SessionController = Ember.ObjectController.extend({
updateReceived: function(data) {
console.log(data);
DS.defaultStore.load(App.Choice, data.choice);
DS.defaultStore.load(App.Question, data.question);
}
});
Notice the console.log(data) part. Every single time I send updated data via websockets, updateReceived is called and the correct data is logged every time, but DS.defaultStore.load(...) only works the first time.
The reason I update both App.Question & App.Choice is because they have a relationship:
App.Question = DS.Model.extend({
"choices" : DS.hasMany('App.Choice')
});
App.Choice = DS.Model.extend({
"question" : DS.belongsTo('App.Question')
});
I don't think the code below is relevant to the issue but just in case someone is interested, this is how I listen for events over websockets (using socket.io):
App.SessionRoute = Ember.Route.extend({
enter: function() {
this.socket = io.connect('http://10.0.1.4')
},
setupController: function(controller, model) {
var self = this;
this.socket.on('update', function(data) {
self.controller.send('updateReceived', data)
})
}
});
Are there any suggestions for how I can continuously load new or updated records directly into the store (and not just once)?
UPDATE:
The code is indeed correct. The new data was loading into the store just fine but I wasn't re-rending a view correctly when new/updated information was loaded into DS.defaultStore
I don't want to delete this question since others may find the information in it useful but vote how you like. I'm sorry I didn't catch this before writing the question.
The app I am working on has an Event-page where users see Events from themselves and friends as well as being able to use an inline event-creator (to create events, on that very same page/route).
To be a bit more precise, the events get all loaded and displayed in a newsfeed style, which works perfectly fine but the problem now is when trying to save a new event-model. I think some code will make this easier to understand.
The routes:
this.resource('newsfeed', function() {
this.route('personal');
this.route('whatever');
});
then in NewsfeedIndexRoute the app has
model: function() {
return App.Event.find();
}
for displaying all Events with an ArrayController at /newsfeed. That works fine.
Furthermroe the app has a NewsfeedRoute and Controller as well so the event-creator is accessible on all sub-routes and for saving an Event we have the following code:
App.NewsfeedRoute = Ember.Route.extend({
setupController: function(controller){
controller.newRecord();
}
});
App.NewsfeedController = Em.ObjectController.extend({
newRecord: function() {
//The following line works but makes the API 'dirty' and an extra model needs to be created
this.set('content', App.Newsfeed.createRecord({title: "new title"}));
//The next line would be preferred, but overrides the displayed models at /newsfeed
//this.set('content', App.Event.createRecord({title: "new title"}));
},
save: function() {
this.get('model').save();
}
});
So the problem now is, when I go to /newsfeed and use the line this.set('content', App.Event.createRecord({title: "new title"})); it overrides everything that gets displayed in the newsfeed/index.hbs template with that one model (so just displaying 'new title'). And when you type in more into the even-creator that gets displayed as well. This is obviously not the behaviour we want. Ideally it should just be separated somehow, then get saved to the Server.
The other line you can see with the Newsfeed model is a work-around and it works fine, but as mentioned in the comment it feels really like a hack and also makes the API kinda dirty, because using the /events endpoint with a POST request would be much more RESTful.
So does anyone have any idea, if there is any way to achieve that right now with ember-data?
There are many ways to accomplish this in ember. Seems like you are pretty close to a good solution but what's missing in this case is an EventController. It should look a lot like what you'd had in App.NewsfeedController.
App.EventController = Em.ObjectController.extend({
newRecord: function() {
this.set('content', App.Event.createRecord({title: "new title"}));
},
save: function() {
this.get('model').save();
}
});
Now in your template, use the {{render}} helper to add the
{{render event}}
And define a event.hbs template.
I'm using an ArrayController in my application that is fed from a Ember Data REST call via the application's Router:
postsController.connectOutlet('comment', App.Comment.find({post_id: post_id}));
For the Post UI, I have the ability to add/remove Comments. When I do this, I'd like to be able to update the contentArray of the postsController by deleting or adding the same element to give the user visual feedback, but Ember Data is no fun:
Uncaught Error: The result of a server query (on App.Comment) is immutable.
Per sly7_7's comment below, I just noticed that the result is indeed DS.RecordArray when there is no query (App.Comment.find()), but in the case where there is a query (App.Comment.find({post_id: post_id}), a DS.AdapterPopulatedRecordArray is returned.
Do I have to .observes('contentArray') and create a mutable copy? Or is there a better way of doing this?
Here is what I ended up implementing to solve this. As proposed in the question, the only solution I know about is to create a mutable copy of the content that I maintain through add and deletes:
contentChanged: function() {
var mutableComments = [];
this.get('content').forEach(function(comment) {
mutableComments.pushObject(comment);
});
this.set('currentComments', mutableComments);
}.observes('content', 'content.isLoaded'),
addComment: function(comment) {
var i;
var currentComments = this.get('currentComments');
for (i = 0; i < this.get('currentComments.length'); i++) {
if (currentComments[i].get('date') < comment.get('date')) {
this.get('currentComments').insertAt(i, comment);
return;
}
}
// fell through --> add it to the end.
this.get('currentComments').pushObject(comment);
},
removeComment: function(comment) {
this.get('currentComments').forEach(function(item, i, currentComments) {
if (item.get('id') == comment.get('id')) {
currentComments.removeAt(i, 1);
}
});
}
Then in the template, bind to the this computed property:
{{#each comment in currentComments}}
...
{{/each}}
I'm not satisfied with this solution - if there is a better way to do it, I'd love to hear about it.
A comment will be too long...
I don't know how do you try to add a record, but you can try to do this: App.Comment.createRecord({}). If all goes right, it will update automatically your controller content. (I think the result of App.Comment.find() works as a 'live' array, and when creating a record, it's automatically updated)
Here is how we do this in our app:
App.ProjectsRoute = Ember.Route.extend({
route: 'projects',
collection: Ember.Route.extend({
route: '/',
connectOutlets: function (router) {
router.get('applicationController').connectOutlet({
name: 'projects',
context: App.Project.find()
});
}
})
and then, the handler of creating a project (in the router):
createProject: function (router) {
App.Project.createRecord({
name: 'new project name'.loc()
});
router.get('store').commit();
},
Just for the record: as of today (using Ember Data 1.0.0-beta), the library takes this situation into account. When a record in an array gets deleted, the array will be updated.
If you try to delete an element on that array manually, for example by using .removeObject(object_you_just_deleted) on the model of the containing controller (which is an ArrayController, hence its model an array of records), you'll get an error like:
"The result of a server query (on XXXXX - the model you try to update manually) is immutable".
So there is no need anymore to code by hand the deletion of the record from the array to which it belonged. Which is great news because I felt like using ED and working it around all the time... :)
Foreword
I had a similar problem and found a little tricky solution. Running through the Ember-Data source code and API docs cleared for me the fact that AdapterPopulatedRecordArray returns from the queried find requests. Thats what manual says:
AdapterPopulatedRecordArray represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the AdapterPopulatedRecordArray.
So the good reason for immutability is that this data is controlled by the server. But what if I dont need that? For example I have a Tasklist model with a number of Tasks and I find them in a TasklistController in a way like
this.get('store').find('task',{tasklist_id: this.get('model').get('id')})
And also I have a big-red-button "Add Task" which must create and save a new record but I dont want to make a new find request to server in order to redraw my template and show the new task. Good practice for me will be something like
var task = this.store.createRecord('task', {
id: Utils.generateGUID(),
name: 'Lorem ipsum'
});
this.get('tasks').pushObject(task);
In that case I got announced error. But hey, I want to drink-and-drive!
Solution
DS.AdapterPopulatedRecordArray.reopen({
replace: DS.RecordArray.replace
})
So that's it. A little "on my own" ember flexibility hack.