How to update/edit record in emberjs? - ember.js

I have collected data from fixture and displayed in form of table.
Also,i have added two column one is edit another is delete now i want to edit specific row.
On click of edit i have populated data on modal window with one update button and i want to update changes on click of update.
Here is my code :
Store :
Grid.Store = DS.Store.extend({adapter: 'DS.FixtureAdapter'});
Router:
Grid.Router.map(function () {
this.resource('mainview', { path: '/' });
});
Grid.MainviewRoute = Ember.Route.extend({
model: function () {
return Grid.ModalModel.find();
}
});
Model :
Grid.ModalModel = DS.Model.extend({
fname: DS.attr('string'),
lname: DS.attr('string'),
email: DS.attr('string'),
contactno: DS.attr('string'),
gendertype: DS.attr('boolean'),
contactype: DS.attr('number')
});
Grid.ModalModel.FIXTURES = [
{
id: 1,
fname: "sachin",
lname: "gh",
email: "gh",
contactno: "4542154",
gendertype: true,
contactype: 1
},
{
id: 2,
fname: "amit",
lname: "gh",
email: "gh",
contactno: "4542154",
gendertype: true,
contactype: 1
},
{
id: 3,
fname: "namit",
lname: "gh",
email: "gh",
contactno: "4542154",
gendertype: true,
contactype: 1
}
];
Controller :
Grid.MainviewController = Ember.ArrayController.extend({
contentChanged: function() {
this.get('content').forEach(function(item){
var serializer = DS.RESTSerializer.create();
var json_data = serializer.serialize(item);
console.log(JSON.stringify(json_data));
});
}.observes('content.#each'),
showmodal: function(){
$('#modal').modal();
},
showeditmodal: function(){
var rowindex_table = 1;
var contactype = 0;
var post = Grid.ModalModel.find(rowindex_table);
var serializer = DS.RESTSerializer.create();
var cont_edit_data = serializer.serialize(post);
console.log(JSON.stringify(cont_edit_data));
this.set('obj_form_edit_data.cont_data.fname', cont_edit_data["fname"]);
this.set('obj_form_edit_data.cont_data.lname', cont_edit_data["lname"]);
this.set('obj_form_edit_data.cont_data.email', cont_edit_data["email"]);
this.set('obj_form_edit_data.cont_data.contactno', cont_edit_data["contactno"]);
if(cont_edit_data["gendertype"] == true){
this.set('male', true);
$(".cssmale").addClass("active");
}else{
this.set('female', true);
$(".cssfemale").addClass("active");
}
$('.selectpicker').val(cont_edit_data['contactype']);
$('.selectpicker').selectpicker('render');
$('#editmodal').modal();
},
isMale: false,
isFemale: false,
obj_form_edit_data : Ember.Object.create({
cont_data:{
fname : "",
lname : "",
email : "",
contactno : "",
gendertype : "",
contactype : 0
}
}),
gendertype: function(){
this.set('isMale', !this.get('isMale'));
},
savecontact: function(){//save data in local storage
var fname = this.obj_form_edit_data.get('cont_data.fname');
var lname = this.obj_form_edit_data.get('cont_data.lname');
var email = this.obj_form_edit_data.get('cont_data.email');
var contactno = this.obj_form_edit_data.get('cont_data.contactno');
var gendertype = ((this.get('isMale') == true) ? true : false);
var contactype = $(".selectpicker").text();
//Clear view first
this.set('obj_form_edit_data.cont_data.fname', '');
this.set('obj_form_edit_data.cont_data.lname', '');
this.set('obj_form_edit_data.cont_data.email', '');
this.set('obj_form_edit_data.cont_data.contactno', '');
this.set('isMale',false);
this.set('isFemale',false);
$('.selectpicker').val('0');
$('.selectpicker').selectpicker('render');
Grid.ModalModel.createRecord({
fname: fname,
lname: lname,
email: email,
contactno: contactno,
gendertype: gendertype,
contactype: contactype
});
this.get('store').commit();
},
updatecontact: function(){
this.get('store').commit();
}
updatecontact is used to update record on click of update button but it is throwing an error
Uncaught TypeError: Object [object Object] has no method 'commit'
Can anyone tell me how to update record in such case?

Related

How do you save a many-to-many relationship in Ember and Firebase

Let's say we have many medicines that can be prescribed to many patients. Our model would look like this:
App.Medicine = DS.Model.extend({
name: DS.attr(),
patients: DS.hasMany('user', { async: true }),
});
App.User = DS.Model.extend({
name: DS.attr(),
medicines: DS.hasMany('medicine', { async: true })
});
In this scenario, how do we save records to a Firebase store?
App = Ember.Application.create();
App.ApplicationAdapter = DS.FirebaseAdapter.extend({
firebase: new Firebase('https://YOUR_FIREBASE.firebaseio.com/')
});
App.Router.map(function(){ });
App.Medicine = DS.Model.extend({
name: DS.attr(),
patients: DS.hasMany('user', { async: true }),
});
App.User = DS.Model.extend({
name: DS.attr(),
medicines: DS.hasMany('medicine', { async: true })
});
App.IndexRoute = Ember.Route.extend({
model: function() {
var medicines = this.store.find('medicine');
var users = this.store.find('user');
return {
medicines: medicines,
users: users
};
},
actions: {
savePost: function(){
var store = this.store;
var medicine1 = store.createRecord('medicine', {name: 'aspirin'});
var patient1 = store.createRecord('user', {name: 'Jane'});
var patient2 = store.createRecord('user', {name: 'Peter'});
medicine1.save()
.then(function(){
return Ember.RSVP.Promise.all([
patient1.save(),
patient2.save()
])
.then(function(){
var promises = [];
var patientsOfMedicine1 = medicine1.get('patients');
var medicinesOfPatient1 = patient1.get('medicines');
var medicinesOfPatient2 = patient2.get('medicines');
promises.push(patientsOfMedicine1, medicinesOfPatient1, medicinesOfPatient2);
return Ember.RSVP.Promise.all(promises);
})
.then(function(arrayOfAttachedArrays){
var promises = [];
var patientsOfMedicine1 = arrayOfAttachedArrays[0];
var medicinesOfPatient1 = arrayOfAttachedArrays[1];
var medicinesOfPatient2 = arrayOfAttachedArrays[2];
patientsOfMedicine1.addObjects(patient1, patient2);
medicinesOfPatient1.addObject(medicine1);
medicinesOfPatient2.addObject(medicine1);
promises.addObjects(medicine1.save(),patient1.save(),patient2.save());
return Ember.RSVP.Promise.all(promises);
});
});
}
}
});
Notes:
Thanks to David Govea for showing me how this works.
If there's a better way to do this, please post below.

Set multiple data with Ember and make it persist on Firebase

I am trying to set data from two models (that has hasMany & belongsTo relationship) and save them to firebase.
'list' data ends up being saved to firebase but not user data.
I think I'm doing something wrong at step 3. I'd appreciate your help!
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('list');
},
actions: {
createList: function() {
var newListTitle = this.controllerFor('lists').get('newListTitle');
var username = this.get('session.user.displayName');
alert(this.get('session.user.displayName'));
if (Ember.isBlank(newListTitle)) { return false; }
//1
var list = this.store.createRecord('list', {
title: newListTitle,
user: username,
});
//2
this.controllerFor('lists').set('newListTitle', '');
var _this = this;
//3
list.save().then(function(list) {
user.get('lists').addObject(list);
user.save();
_this.transitionTo('lists.show', list); //4
});
}
}
});
Restructured your adding logic as well as user defined models, also modified your route, which could look like this in Edit and View mode. Meaning you can have more than one item returned from "model".
// Update models
App.List = DS.Model.extend({
value: DS.attr('string')
});
App.User = DS.Model.extend({
name: DS.attr('string')
});
App.UserLists = DS.Model.extend({
user: DS.belongsTo('user'),
list: DS.belongsTo('list')
});
export default Ember.Route.extend({
LIST:SHOW ROUTE
model: function(params) {
var store = this.get('store');
var userPromise = store.find('user', params.id);
return Ember.RSVP.hash({
user: userPromise,
userList : userPromise.then(function(user) {
return store.find(userList, { WhereUserIdIs : user.get('id') })
});
});
},
actions: {
createList: function() {
var self = this;
var failure = function(reason) {
// handle stuff
};
var list = this.store.createRecord('list', {
title: this.get('title'),
});
var user = this.get('user');
var usersList = store.createRecord('userList', {
'user': user,
'list': list
});
list.save().then(function(list) {
user.save().then(function() {
userList.save().then(function() {
self.transitionTo('lists.show', list.get('id'));
}, failure);
}, failure);
}, failure);
}
});

store.updateRecord is not a function in ember.js

I am newbie to ember.js, I am using ember-1.9.1.js and ember-data for my project.
For back-end configuration I have created a REST API with core php and the db is MySQL.
Now I can create new records (posts) from client side using with DS.RESTAdapter's "createRecord" function.
But I don't know how to update a Record (post) with DS.RESTAdapter's "updateRecord" function.
When I try to call the "updateRecord" function from "App.PostController (doneEditing)" I got this error:
Uncaught TypeError: store.updateRecord is not a function --------- app.js
app.js code below
App = Ember.Application.create();
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('home');
}
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'pran/webapp/rest_adapter/api',
createRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var url = "api/new_post";
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
},
updateRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var id = snapshot.id;
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
App.Store = DS.Store.extend({
revision: 12,
adapter: 'App.ApplicationAdapter'
});
App.Post = DS.Model.extend({
title: DS.attr('string'),
author: DS.attr('string'),
date: DS.attr('date'),
excerpt: DS.attr('string'),
body: DS.attr('string')
});
App.Router.map(function() {
this.resource('home');
this.resource('about');
this.resource('posts', function(){
this.resource('post', { path: ':post_id' });
});
this.resource('newstory' , {path : 'story/new'});
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return this.store.filter('post', { id: true }, function(post) {
return post.get('id');
return this.store.find('post');
});
}
});
App.PostRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('post', params.post_id);
}
});
App.NewstoryController = Ember.ObjectController.extend({
actions :{
save : function(){
var title = $('#title').val();
var author = $('#author').val();
var excerpt = $('#excerpt').val();
var body = $('#body').val();
var store = this.get('store');
var new_post = store.createRecord('post',{
title : title,
author : author,
date : new(Date),
excerpt : excerpt,
body : body
});
new_post.save();
this.transitionToRoute('posts');
}
}
});
App.PostController = Ember.ObjectController.extend({
isEditing: false,
actions: {
edit: function() {
this.set('isEditing', true);
},
doneEditing: function() {
this.set('isEditing', false);
var title = $('#title').val();
var excerpt = $('#excerpt').val();
var body = $('#body').val();
var store = this.get('store');
var update_post = store.updateRecord('post',{
title : title,
excerpt : excerpt,
body : body
});
update_post.save();
}
}
});
Somebody please suggest a way to fix the issue.
updateRecord is adapter's method not store's
so try next:
store.adapterFor(App.Post).updateRecord(...
this is fast fix
And better create Post object and call method .save() - it's not good practice to work with adapter from controller like
App.Post.create({
title : title,
excerpt : excerpt,
body : body
}).save();
P.S. The final solution was
App.NewstoryController = Ember.ObjectController.extend({
actions :{
save : function(){
var title = $('#title').val();
var author = $('#author').val();
var excerpt = $('#excerpt').val();
var body = $('#body').val();
var store = this.get('store');
var new_post = store.createRecord('Post',{
title : title,
author : author,
date : new(Date),
excerpt : excerpt,
body : body
});
new_post.save();
this.transitionToRoute('posts');
}
}
});

ember Uncaught Error: assertion failed: Emptying a view in the inBuffer state

I get this assertion when run the code below:
Emptying a view in the inBuffer state is not allowed and should not
happen under normal circumstances. Most likely there is a bug in your
application. This may be due to excessive property change
notifications.
Link to demo:
http://plnkr.co/edit/s3bUw4JFrJvsL690QUMi
var App = Ember.Application.create({
Store: DS.Store.extend({
revision: 4,
adapter: DS.FixtureAdapter.create()
}),
Router: Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: "/",
connectOutlets: function(router){
var person;
person = App.Person.find(657);
person.addObserver("isLoaded", function() {
return router.get('router.applicationController').connectOutlet("things", person.get("things"));
});
}
})
})
}),
ApplicationController: Em.Controller.extend(),
ApplicationView: Em.View.extend({
template: Em.Handlebars.compile("{{outlet}}")
}),
ThingsController: Em.ArrayController.extend({
thingTypes: (function() {
return App.ThingType.find();
}).property()
}),
ThingsView: Em.View.extend({
template: Em.Handlebars.compile([
'{{#each controller.thingTypes}}',
'{{this.name}}',
'{{/each}}',
'{{#each controller.content}}',
'{{this.title}}',
'{{/each}}'].join(""))
}),
//MODELS
Person: DS.Model.extend({
things: DS.hasMany('App.Thing', {
embedded: true
})
}),
Thing: DS.Model.extend({
description: DS.attr('string'),
thingType: DS.belongsTo("App.ThingType", {
embedded: true
}),
title: (function() {
return this.get("thingType.name");
}).property("description")
}),
ThingType: DS.Model.extend({
name: DS.attr("string")
})
});
App.Person.FIXTURES = [
{
id: 657,
things: [
{
id: 1,
description: "Some text",
thing_type: {
id: 1,
name: "type 1"
}
}, {
id: 2,
description: "Some text",
thing_type: {
id: 2,
name: "type 2"
}
}
]
}
];
App.ThingType.FIXTURES = [
{
id: 1,
name: "type 1"
}, {
id: 2,
name: "type 2"
}, {
id: 3,
name: "type 3"
}
];
Why is this happening?
I was having the same error while trying to load a list of dropdown values from fixtures. What resolved it was overriding queryFixtures on the fixture adapter:
App.FixtureAdapter = DS.FixtureAdapter.extend
latency: 200
queryFixtures: (records, query, type) ->
records.filter (record) ->
for key of query
continue unless query.hasOwnProperty(key)
value = query[key]
return false if record[key] isnt value
true
I probably wouldn't have figured it out had I not set the latency first. Then the error was a bit more descriptive.
a bit late I guess... but I got it to work here:
http://plnkr.co/edit/hDCT4Qy1h5aE6GjM76qp
Didn't change the logic but where its called
I modified your router like this:
Router: Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: "/",
connectOutlets: function(router) {
var person;
router.set('router.applicationController.currentPerson', App.Person.find(657));
}
})
})
})
And created an ApplicationController:
ApplicationController: Em.Controller.extend({
currentPerson: null,
currentPersonLoaded: function() {
this.connectOutlet("things", this.get("currentPerson.things"));
}.observes("currentPerson.isLoaded"),
})
I dont know if this is the output you wished but the bug vanished!

emberjs - property fires twice

Why does the "fullName" function in this code execute twice?
Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: function() {
console.log('Full name function...');
var firstName = this.get('firstName');
var lastName = this.get('lastName');
return firstName + ' ' + lastName;
}.property('firstName', 'lastName')
});
App.tom = Person.create({
firstName: "Tom",
lastName: "Dale"
});
App.UsersView = Ember.View.create({
templateName: 'users',
users: [App.tom]
});
Later in google-chrome console:
App.tom.set('firstName', 'John')
This outputs to log twice.
Seems like a bug, indeed (added a JSFiddle to illustrate: http://jsfiddle.net/MikeAski/GRvgt/)...
The view is rerendered, and the computed property not cached yet. :-(