ember.js `afterModel` event handler changes not reflected in Template - ajax

I have a route in which I use Ajax (not Ember Data) to pull a record, a costcentre, off the server. The record is intended to populate a template for subsequent edits.
Before the fetch, in beforeModel, an empty costcentre is created using createRecord. After the model processing is complete, in afterModel, the returned data is used to populate the costcentre object in the Data Store.
The fetch of the data is successful and in the debugger the update of the locally stored DS object can be seen to have worked but the changes are not seen in the template.
How can I get the template to populate with the data returned from the server ?
In the route I have this :
beforeModel: function(transition) {
this.set('ccToEdit', this.store.createRecord('costcentre'));
},
model(params) {
return getCCByCCIdent( this.urlbase,
this.currentMOP.currentMOP,
ENV.APP.MATClientCode,
params.cceIdentifier_to_edit);
},
afterModel(ccs, transition) {
//I'm testing this with an API end point that returns a
//list but there will only ever be one item in the list
this.ccToEdit.setProperties(ccs[0]);
},
The getCCByCCIdent looks like this :
export const getCCByCCIdent = function(urlbase, currentMOP, clientCode, targetCostCentreIdent) {
return new Promise(function (resolve, reject) {
if (targetCostCentreIdent.length == 0)
{
resolve([])
}
else
{
var theUrl = `${urlbase}/costcentres/${currentMOP}/${clientCode}/${targetCostCentreIdent}`;
$.ajax({
type: 'GET',
url: theUrl,
success: function (response) {
resolve(response);
},
error: function (request, textStatus, error) {
reject(error);
}
});
}
})
}

The simplest way to do this would be to do a then() on the promise being returned from your Ajax call, set appropriate values after that and then return your model:
model(params) {
return getCCByCCIdent(
this.urlbase,
this.currentMOP.currentMOP,
ENV.
params.cceIdentifier_to_edit
).then(ccs => {
let costCentre = this.store.createRecord('costcentre');
costCentre.setProperties(ccs[0]);
return costCentre;
});
},

Related

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

How to get the data from BehaviorSubject after its completed?

I have a function that returns a BehaviorSubject but when I try to use the data I get back from the function I need to use it once all the data is back, is there a way to know when the BehaviorSubject is done pulling all the data?
I tried using .finally but it never gets called. Here is the code I'm using.
getData() {
let guideList = '';
this.getChildren(event.node)
.subscribe(
function(data) {
console.log('here');
guideList = data.join(',');
},
function(err) {
console.log('error');
},
function() {
console.log('done');
console.log(guideList);
}
);
}
getChildren(node: TreeNode) {
const nodeIds$ = new BehaviorSubject([]);
//doForAll is a promise
node.doForAll((data) => {
nodeIds$.next(nodeIds$.getValue().concat(data.id));
});
return nodeIds$;
}
Attached is a screen shot of the console.log
Easiest way is to just collect all the data in the array and only call next once the data is all collected. Even better: don't use a subject at all. It is very rare that one ever needs to create a subject. Often people use Subjects when instead they should be using a more streamlined observable factory method or operator:
getChildren(node: TreeNode) {
return Observable.defer(() => {
const result = [];
return node.doForAll(d => result.push(d.id)).then(() => result);
});
}

How to prevent validate function call while calling model.save in backbone JS

I have a backbone view where I call model.save to create/updated date submitted in the form. Before calling the save I explicitly call model.isValid(true) to validate the form fields then I process the form data to make it ready for API expected format (by adding or modifying additional fields) and then make call to mode.save function which is again triggering validate function where the validations are getting failed due to the modified data. As I have already called the isValid function explicitly, I want to prevent the call again during save. How can I do it in backbone. Here is sample code.
var data = Backbone.Syphon.serialize($(e.currentTarget).closest('form.my_form')[0]));
this.model.set(data);
if(this.model.isValid(true)) {
data['metas'] = this.context.metaData;
data['metas'][0]['locale'] = this.parentObj.model.get('locale');
data['metas'][0]['name'] = data['name'];
delete data['name'];
}
var tempDynAttrs = [];
if(data['dynamicAttributes']){
$.each(data['dynamicAttributes'], function(index,obj) {
if(obj['attributeValue'] !== null && obj['attributeValue'] !== undefined ) {
tempDynAttrs.push({
attributeName: obj['attributeName'],
attributeValue: [obj['attributeValue']],
locale: data['defaultLocale'],
status: 'active'
});
}
});
}
data['dynamicAttributes'] = tempDynAttrs;
this.model.save(data, {
url: this.model.url(),
patch: true,
success : function(model, response) {
$('#headerMessage').html('Data is updated successfully');
},
error : function(model, response) {
$('#headerMessage').html('Error updating data');
}
});
} else {
$('#formPanel').animate({
scrollTop: $('.has-error').first().offset().top-50
}, 100);
return false;
}
Try passing {validate:false} in the save options, like
book.save({author: "Teddy"}, {validate:false});
According to change log of version 0.9.10:
Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the {validate:true} option is passed.
So passing {validate:false} should do the trick.

Dojo Cache - Tree - Uncaught TypeError: object is not a function

I am trying to use a data store cache with a tree.
I am getting Uncaught TypeError: object is not a function error.
I have tested the data and it is being pulled correctly.
I have checked the JSON and it is also correct.
Where am I going wrong?
require(["dojo/store/JsonRest"
, "dojo/store/Memory"
, "dojo/store/Cache"
, "dojo/json"
, "dijit/tree/ObjectStoreModel"
, "dijit/Tree"
, "dojo/domReady!"],
function (JsonRest, Memory, Cache, ObjectStoreModel, Tree) {
var restStore = new JsonRest({ target: "/DataStore/", idProperty: "id" });
var memoryStore = new Memory({
idProperty: "id",
getChildren: function (object) {
return this.query({ parent: object.id });
}
});
var store = new Cache(restStore, memoryStore);
store.query({ type: "index" }).forEach(function (item) {
console.log(item.name);
});
var docModel = new ObjectStoreModel(
{
store: store,
getRoot: function (onItem) {
this.store.get("index").then(onItem);
},
mayHaveChildren: function (object) {
return object.type === "folder" || object.type === "root";
}
});
var docTree = new Tree({
model: docModel,
onOpenClick: true,
onClick: function (item) {
if (item.type == "link") {
OpenLink(item.link);
}
},
persist: false
}, "divTree");
docTree.startup();
});
This has to do how Cache works. The first time store.get() is called, it uses the JsonRest store which returns a Promise. A Promise has a then() function so there is no problem. The next time it's called, it uses the Memory store which returns your JavaScript object itself. Your JavaScript object has no then() function, so an error is thrown. This can be fixed by surrounding the store.get() in a when().
Try changing
this.store.get("index").then(onItem);
to
when(this.store.get("index")).then(onItem);
Take a look here for more details.

Angularjs multiple ajax requests optimization

I am still learning Angular JS and have this controller which is making two ajax requests to the lastfm api using different parameters. I want to know when each request has been finished, so that I can display a loading indicator for both requests. I have researched it and read about promises and the $q service but cant get my head around how to incorporate it into this. Is there a better way to set this up? and how can I know when each request is done. Thanks.
angular.module('lastfm')
.controller('ProfileCtrl', function ($scope, ajaxData, usersSharedInformation, $routeParams) {
var username = $routeParams.user;
//Get Recent tracks
ajaxData.get({
method: 'user.getrecenttracks',
api_key: 'key would go here',
limit: 20,
user: username,
format: 'json'
})
.then(function (response) {
//Check reponse for error message
if (response.data.message) {
$scope.error = response.data.message;
} else {
$scope.songs = response.data.recenttracks.track;
}
});
//Get user info
ajaxData.get({
method: 'user.getInfo',
api_key: 'key would go here',
limit: 20,
user: username,
format: 'json'
})
.then(function (response) {
//Check reponse for error message
if (response.data.message) {
$scope.error = response.data.message;
} else {
$scope.user = response.data.user;
}
});
});
I have this factory which handles all the requests
angular.module('lastfm')
.factory('ajaxData', function ($http, $q) {
return {
get: function (params) {
return $http.get('http://ws.audioscrobbler.com/2.0/', {
params : params
});
}
}
});
Quite easy using $q.all(). $http itself returns a promise and $q.all() won't resolve until an array of promises are resolved
var ajax1=ajaxData.get(....).then(....);
var ajax2=ajaxData.get(....).then(....);
$q.all([ajax1,ajax2]).then(function(){
/* all done, hide loader*/
})

Resources