Initializing a store's data in Extjs - javascript

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.

Related

EXTJS Extending Ext.data.JsonStore

I'm an ExtJS (I'm using version 5.1) newbie and I'm trying to split a monolithic single file application in different files. I've moved a store outside in a separate file. This is the store in the separate file:
Ext.define("MT.store.MicroProfilerStore", {
extend: "Ext.data.JsonStore",
singleton : true,
model : 'MT.model.MicroProfilerModel',
storeId: "micro_profiler_store",
autoLoad: false,
proxy: {
type: 'ajax',
url: './backend/profiler.php',
reader: {
type: 'json',
rootProperty: 'answers'
}
}
});
If I use this file the ajax request is correct and I can see the reply but it looks like the store is ignoring the rootProperty and instead of having the array of answers in the store.getData() I have a single item array with the first value that is the entire response converted to javascript like:
[{success: 'true', answers: [{}, {}]}]
But If I create the store directly without subclassing using Ext.create("Ext.data.JsonStore", {...}) it's working!
The hack that I've found after a day of trying that allows me to keep a separate file for the store is this:
Ext.define("MT.store.MicroProfilerStore", function(){
Ext.require(['MT.model.MicroProfilerModel'], function(){
Ext.create("Ext.data.JsonStore", {
singleton : true,
model : 'MT.model.MicroProfilerModel',
storeId: "micro_profiler_store",
autoLoad: false,
proxy: {
type: 'ajax',
url: './backend/profiler.php',
reader: {
type: 'json',
rootProperty: 'answers'
}
}
});
});
return {};
});
Then I can get the store using StoreManger.lookup(). Ok it's working fine but the question is why ?
PS
I've already tried preloading the model before the store, explicity requiring the model and the store in many place It doesn't looks like a precedence error
Thanks for your help
We have many stores which could be made singleton, but it seems that singleton:true isn't part of ExtJS best practices.
If we need a "singleton store", which is like 90% of the time, we still make a normal store, but add that store to the stores array in Application.js, so that the instance is created before Application launch. What makes the store a singleton is a storeId, by which it is referenced from everywhere. All our singleton stores are defined using a special constructor/callParent construction, because we didn't get reader rootProperty to work otherwise:
Ext.define('MyApp.store.Directories',{
extend: 'Ext.data.Store',
storeId: 'DirectoryStore',
constructor: function() {
var me = this;
this.callParent([{
proxy: {
type: 'ajax',
headers:{'Accept':'application/json'},
noCache: true,
pageParam: false,
startParam: false,
limitParam: false,
extraParams: {
q: 'directory'
},
url: '../api/AddressBook',
reader: {
type: 'json',
rootProperty: 'data'
}
},
autoLoad: true
}]);
}
});
The special constructor/callParent part makes the difference here. We don't exactly know WHY it works, but it works - we copied that approach from Sencha Architect-generated code. If we now need that store's content anywhere, we do as follows:
xtype:'combo',
name:'Directory',
store:'DirectoryStore' // <- reference by storeId!
The storeId reference fails if we don't add the store to the stores array in Application.js, where we should keep a list of all "singleton" stores:
Ext.define('MyApp.Application', {
extend: 'Ext.app.Application',
name: 'MyApp',
views: [
/* Allgemein */
...
],
controllers: [
'Configuration',
...
],
stores: [
'Directories',
...
]

Save multiple models in loopback

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'}
}
);

using extjs Store from Different JS file

this is CreateUI.js
Ext.onReady(function() {
Ext.QuickTips.init(); //tips box
Ext.define('RouteModel', {
extend: 'Ext.data.Model',
fields: [{name: '_id', type: 'number'}, 'Route_Code','Route_Name','Name','AddBy_ID']
});
Ext.override(Ext.data.Connection, {
timeout : 840000
});
var RouteNameStore = Ext.create('Ext.data.JsonStore', {
model: 'RouteModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'get-routename.php',
api: {
create: 'insert-routename.php',
//read: 'http://visual04/ModuleGestion/php/Pays.php?action=read',
update: 'update-routename.php',
//destroy: 'http://visual04/ModuleGestion/php/Pays.php?action=destroy'
},
reader: {
type: 'json',
idProperty: '_id'
},
writer: {
type: 'json',
id: '_id'
}
}
});
})
routename.js
RouteNameStore.add ({
Route_Code: txtAddRouteCode,
Route_Name: txtAddRouteName,
AddBy_ID: getCookie('User_ID')
});
and this is the index.html page to link this two js file
<script type="text/javascript" src="CreateUI.js?"></script>
<script type="text/javascript" src="routename.js?"></script>
fire bug error
ReferenceError: RouteNameStore is not defined
RouteNameStore.add ({
I m trying to use the JSonStore on different JavaScript file, but failed.
how to fix this? thanks
You define RouteNameStore as local varible inside Ext.onReady handler function.
Because varible scope is inside function, it is not accessible from other functions.
If you want more informations about variable scopes in JavaScript you can look here: What is the scope of variables in JavaScript?
For accessing stores in ExtJS, you can add to your store configuration unique storeId and then get your store in other object by Ext.data.StoreManager
// create store
Ext.create('Ext.data.Store', {
...
storeId: 'myStore'
...
});
// get existing store instance
var store = Ext.data.StoreManager.lookup('myStore');

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