Save multiple models in loopback - javascript

I'm doing research on loopback and was wondering if it's possible to save to multiple models from one request. Say.. an Post has many Tags with many Images. A user form would have the following:
Post Title
Post Description
Tag Names (A multi field. E.g.: ['Sci-Fi', 'Fiction', 'BestSeller']
Image File (Hoping to process the file uploaded to AWS, maybe with skipper-s3?)
How would I be able to persist on multiple models like this? Is this something you do with a hook?

You can create RemoteMethods in a Model, which can define parameters, so in your example you could create something like this in your Post model:
// remote method, defined below
Post.SaveFull = function(title,
description,
tags,
imageUrl,
cb) {
var models = Post.app.Models; // provides access to your other models, like 'Tags'
Post.create({"title": title, "description": description}, function(createdPost) {
foreach(tag in tags) {
// do something with models.Tags
}
// do something with the image
// callback at the end
cb(null, {}); // whatever you want to return
})
}
Post.remoteMethod(
'SaveFull',
{
accepts: [
{arg: 'title', type: 'string'},
{arg: 'description', type: 'string'},
{arg: 'tags', type: 'object'},
{arg: 'imageUrl', type: 'string'}
],
returns: {arg: 'Post', type: 'object'}
}
);

Related

Array Type in Loopback custom remote methode

I have defined a custom remote method in loopback trying to post some data.
Here is the code of the methode definition:
Workout.prototype.greet = function(userId, exercises, cb) {
cb(null, userId + ' ' + this.id);
}
Workout.remoteMethod('prototype.greet', {
accepts: [{arg: 'userId', type: 'string', required: true, description:"MyUserId for who created the challenge", http: { source: 'query' }},
{arg: 'exercises', type: 'array', required: true, description:"Array of exercises which should be added", http: { source: 'body' }}],
returns: {arg: 'greeting', type: 'object'},
});
When posting data with an empty array in exercises everything works fine see:Working without data. But when I insert any information into the array I get an error see: Not Working with data
Hope somebody can help me. Thank you!
You see that error because you send malformed JSON. You omit quotation marks around id. It should look like this:
["id": "1"]

Extjs 5.0 model POST values not received on server side (working Extjs 4.2)

I am upgrading our Extjs 4.2 app to Extjs 5.0.
I am able to bring up all the read only pages but i am getting issues when i try to update/save the data. I will really appreciate your help!!
My model data values are not showing up on the server side, i am able to print model with console.log(model) and it has all the values , but on the server side it only has id and all the other parameters are showing as null.
Here is proxy in the model :
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
id: 'user',
proxy: {
type: 'rest',
url : '/rest/update/user',
listeners: {
exception: function(proxy, response, operation) {
Ext.Msg.alert('Failed', 'Save the user Failed!');
}
}
},
fields: [
{name: 'id', type: 'int'},
{name: 'userName', type: 'string'},
{name: 'country', type: 'string'}
]
}
The controller :
onUserUpdateAction: function(button, event, action) {
var model = Ext.create('MyApp.model.User');
model.set('id', "123");
model.set('userName', "john");
model.set('country', "usa");
---
model.commit() / without commit() it does not add the id in URL like /user/123
model.save();
}
Here is the server side code :
#PUT
#Consumes({ "application/json" })
#Path("/Update/user/{id}")
updateUser(#PathParam("id") final int id, final User record);
First line log in the implementation class, id is there but all the other values are null
*** In updateUser() method, id : 123, record: User(id=123, **userName=null, country=null**)
The problem here is that you try to fool the Ext. You create new record with id - normally ids are assigned by the server. Therefore, you need to commit it to clear it phantom (new record) flag, so that Ext thinks it is already existing record. But, after commit, the record has no modified fields and, by default, only modified fields are sent to the server. Therefore, you need a writer configured, something like this:
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{name: 'id', type: 'int'},
{name: 'userName', type: 'string'},
{name: 'country', type: 'string'}
],
proxy: {
type: 'rest',
url : 'success.php',
listeners: {
exception: function(proxy, response, operation) {
Ext.Msg.alert('Failed', 'Save the user Failed!');
}
}
,writer:{
type:'json'
,writeAllFields:true
}
}
});

Initializing a store's data in Extjs

I have store that I would like to initialize from a database but I couldn't find a standard init method for the Ext.data.Store. I found a couple of examples with the StoreManager component, but I think that's not what I'm looking for. I have an MVC structure for my app and I'd like to keep it, I only want to initialize my store's data field using a method I define. Could someone explain how to do so?
I either understand you wrong or your question is straight forward. You configure a store with a model like this. That's all. You may just chose a provider(reader/writer) that fit your needs.
// Set up a model to use in our Store
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{name: 'firstName', type: 'string'},
{name: 'lastName', type: 'string'},
{name: 'age', type: 'int'},
{name: 'eyeColor', type: 'string'}
]
});
Ext.define('YourMVCNameSpace.data.UserStore', {
extend: 'Ext.data.Store',
constructor: function (config) {
config = Ext.Object.merge({}, config);
var me = this;
// do what you need with the given config object (even deletes) before passing it to the parent contructor
me.callParent([config]);
// use me forth on cause the config object is now fully applied
},
model: 'User',
proxy: {
type: 'ajax',
url: '/users.json',
reader: {
type: 'json',
root: 'users'
}
},
autoLoad: true
});
Note that the reader will expect a Json result like this:
{"total": 55, "users":["...modeldata.."]}
and is referring to a url like
http://localhost/YourAppDomain//users.json
Place the store as 'User' within the controller store array and retrieve it within the Controller by calling getUserStore() or directly from the Ext.StoreMgr using Ext.StoreMgr.lookup('User');
Note that by convention the Controller (MVC) will override any storeId you set on the store and will just use the name.

How to get data from extjs 4 store

Im stack with ext js 4 at the very beginning. Im trying to get the current user data when starting the application using store. But Im not getting any data from the store, even the store.count return 0.
I found many description how to create store, but not how to access the data in it. I managed to get the data using Ext ajax request, but i think would be better using store and i cant avoid them..
My model:
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
fields: [
'id',
'username',
'email'
]
});
My store looks like:
Ext.define('MyApp.store.User.CurrentUser', {
extend: 'Ext.data.Store',
requires: 'MyApp.model.User',
model: 'MyApp.model.User',
autoLoad: true,
proxy: {
type: 'ajax',
method: 'POST',
url: Routing.generate('admin_profile'),
reader: {
type: 'json',
root: 'user'
}
}
});
The returned json:
{
"success":true,
"user":[{
"id":1,
"username":"r00t",
"email":"root#root.root"
}]
}
And the application:
Ext.application({
name: 'MyApp',
appFolder: '/bundles/myadmin/js/app',
models: ['MyApp.model.User'],
stores: ['MyApp.store.User.CurrentUser'],
//autoCreateViewport: true,
launch: function() {
var currentUser=Ext.create('MyApp.store.User.CurrentUser',{});
/*
Ext.Ajax.request({
url : Routing.generate('admin_profile'),
method: 'POST',
success: function(resp) {
var options = Ext.decode(resp.responseText).user;
Ext.each(options, function(op) {
var user = Ext.create('MyApp.model.User',{id: op.id,username:op.username,email:op.email});
setUser(user);
}
)}
});
*/
currentUser.load();
alert(currentUser.count());
}
});
The problem itself isn't that the store does not contain data, the problem is that the store load is asyncronous therefore when you count the store records, the store is actualy empty.
To 'fix' this, use the callback method of the store load.
currentUser.load({
scope : this,
callback: function(records, operation, success) {
//here the store has been loaded so you can use what functions you like
currentUser.count();
}
});
All the sencha examples have the proxies in the store, but you should actually put the proxy in the model, so that you can use the model.load method. the store inherits the model's proxy, and it all works as expected.
it looks like model.load hardcodes the id though (instead of using idProperty), and it always has to be an int, as far as I can tell.
good luck!

Get records from json store extjs

I have a json store loaded, I need to grab one record from it.
I used : getAt(index), find(), getById(), but no results .
This is my code :
var appSettingReader = new Ext.data.JsonReader({
root: 'results',
},[
{name: 'id', type: 'int', mapping: 'id'},
{name: 'projetId', type: 'int', mapping: 'projetId'},
{name: 'resLevels', type: 'int', mapping: 'resLevels'},
{name: 'maxResToLock', type: 'int', mapping: 'maxResToLock'},
{name: 'maxTimeToLock', type: 'int', mapping: 'maxTimeToLock'},
{name: 'infosToPrint', type: 'string', mapping: 'infosToPrint'}
])
var appSettingStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: 'inc/getSettings.php',
method: 'POST'
}),
baseParams:{task: "app"},
reader : appSettingReader,
sortInfo:{field: 'id', direction: "DESC"}
})
appSettingStore.load();
This code return undefined :
console.log(appSettingStore.getAt(0));
console.log(appSettingStore.find("id","1"));
This is the json string returned from server :
{success:true,"results":[{"id":"1","projetId":"1","resLevels":"1","maxResToLock":"40","maxTimeToLock":"10","infosToPrint":"1_2_3_5","hotlineMail":"admin#app.com"}]}
I've also tested this code :
var records = new Array()
var test = appSettingStore.each(function(rec){
records.push(rec)
})
console.log(records)
and I get an empty array !
PS : This store is not bound to any component;
I just want to read and write to it.
You need to place a callback on the store, that will be fired after it loads. You can then use the data as required.
store.load({
callback : function(r, options, success) {
console.log(r.data)
}
})
It appears the server is returning invalid JSON. Why does your server-side script's output start with "("?
If that's not actually the problem, maybe you should consider accepting some more answers to your questions. People will be more likely to help.
EDIT: Okay, so you're pretty sure you're getting valid json back from the server. Try adding a 'success' property to your server's output.
If that doesn't work, you'll want to dig in a little more. Try adding a callback option to your store's .load(), and look at the stuff that gets passed into the callback. That should help you figure out where things are going wrong.

Categories

Resources