While developping an application I run some code on application launch:
Ext.application({
extend: 'TestApp.Application',
name: 'TestApp',
requires: [
'TestApp.*'
],
// The name of the initial view to create.
launch: async function () {
const store_org = Ext.getStore('Organizations');
const store_event = Ext.getStore('Events');
//more stuff here
}
});
Both stores are well defined:
Ext.define('TestApp.store.Organization', {
extend: 'Ext.data.Store',
storeId: 'Organizations',
alias: 'store.organizations',
model: 'TestApp.model.Organization',
autoLoad: true,
pageSize: 0,
proxy: {
type: 'ajax',
url: TestApp.util.Config.getHost() + '/organization/get-organizations',
withCredentials: true,
reader: {
type: 'json',
rootProperty: '',
},
},
});
I do notice however that while launching the Ext.getStore() function always returns undefined for any store. Is there any way I can "delay" this to the point where the storemanager has fully loaded and these stores do no longer return undefined? (The stores themselves won't be filled with data...).
Just add this to the Ext.application class or to the TestApp.application (which is better)
stores:['TestApp.store.Organization'],
this is an array of all your stores,so if you need to add more just use a comma and write the class path name of the new file
Here is a working example Fiddle
Related
Using ExtJS 6 one can have a store bind to the model and use the methods sync to save or load to load data.
I imagine that if a data is removed from store, upon calling sync the data will be removed from database too.
In my use case, I have different URLs and mandatory Ajax query fields for each action of create/update, load and delete data.
I have only seen examples showing load or save to storage, how can I declare the load, save and delete using Ajax in the same model?
Another doubt I have is that stores themselves can have a proxy, so they can perform those operations too, at least the load operation that I have seen in use. What's the difference between having these on the model or store? What's the best practice?
Example model from Sencha docs (is this only for read?):
Ext.define('MyApp.model.Base', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
type: 'int'
}],
schema: {
namespace: 'MyApp.model', // generate auto entityName
proxy: { // Ext.util.ObjectTemplate
type: 'ajax',
url: '{entityName}.json',
reader: {
type: 'json',
rootProperty: '{entityName:lowercase}'
}
}
}
});
Another example I found on https://examples.sencha.com/extjs/6.0.1/examples/classic/writer/writer.html using the proxy config, this seems more like what I would need as it specifies a URL for each operation:
var store = Ext.create('Ext.data.Store', {
model: 'Writer.Person',
autoLoad: true,
autoSync: true,
proxy: {
type: 'ajax',
api: {
read: 'app.php/users/view',
create: 'app.php/users/create',
update: 'app.php/users/update',
destroy: 'app.php/users/destroy'
},
reader: {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
},
writer: {
type: 'json',
writeAllFields: false,
root: 'data'
},
listeners: {
exception: function(proxy, response, operation){
Ext.MessageBox.show({
title: 'REMOTE EXCEPTION',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}
},
listeners: {
write: function(proxy, operation){
if (operation.action == 'destroy') {
main.child('#form').setActiveRecord(null);
}
Ext.example.msg(operation.action, operation.getResultSet().message);
}
}
});
I believe I can have something like this in my case (this is just an example not tested!):
Ext.define('My.Person.Model', {
proxy: {
type: 'ajax',
api: {
read: 'http://myapiserver/getuser',
create: 'http://myapiserver/upsertuser',
update: 'http://myapiserver/upsertuser',
destroy: 'http://myapiserver/removeuser'
},
reader: {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
},
writer: {
type: 'json',
writeAllFields: false,
root: 'data'
},
// How can I have the parameters for each one?
extraParams : {
isuserUnderage : ' '
, query : '%'
}
}
});
I have no idea how to do this, specially specifying parameters for each type of Ajax request (read, create, update, destroy), I can have an upsert request that will send all fields, but the remove request will require only the ID, the get request can have optional fields for filtering, like filtering persons by name.
Example to be more clear of the problem.
Example data:
[
{
"id": "1",
"name": "Fred",
"age": 21,
"sex": "m"
},
{
"id": "2",
"name": "Susan",
"age": 12,
"sex": "f"
},
{
"id": "3",
"name": "Marcus",
"age": 22,
"sex": "m"
},
{
"id": "4",
"name": "Alex",
"age": 32,
"sex": "m"
}
]
Endpoints example:
Endpoints have parameters, these are mandatory, this means that calling an enpoint without a parameter will cause a server error, also passing a parameter that is not specified will cause a server error! If a parameter is not necessary one can pass a string with a single whitespace .
To read:
Endpoint: http://myapiserver/getuser?query={query}
Name is a filter by name, for example http://myapiserver/getuser?query=fred will bring users with name that has the string fred.
To write, we usually have an upsert, so it works for both insert and update:
Endpoint: http://myapiserver/upsertuser?id={id}&name={name}&age={age}&sex={sex}
So to update we can pass the ID: http://myapiserver/upsertuser?id=1&name=Frederick&age=21&sex=m and to insert we pass an empty string for ID: http://myapiserver/upsertuser?id= &name=Maurice&age=41&sex=m
To remove:
Endpoint: http://myapiserver/removeuser?id={id}
Example: http://myapiserver/removeuser?id=1, removes person with ID 1.
Because you say it's mandatory to use GETs with query params, I would encourage you to rethink your tech stack because the RESTful verbs really make it more clear what your action is, and you remove the actual action from your URL routes. However, I know sometimes this is totally out of our control, so I'll try my best here... I have to say, I've never experienced something like this, so I don't know if what I'm showing here is a best practice.
I can't show a true implementation because Sencha Fiddle is a simple sandbox, not meant for actual server-side implementations. I'm also assuming that you're using the classic toolkit, but if you need it in modern, it's a fairly easy port that you can do.
I prefer the proxy inside of the model for several reasons... if I need to use this model in several different stores throughout my app, then each store will inherit the same proxy. If I want to use the same model, but I don't want its proxy, I can simply override it when defining the store. Also, if the proxy doesn't exist on the model, then the framework assumes what your URL should be, which doesn't work when I want to use models individually.
I think I've come up with what you're asking for in this Fiddle. Really the core of what you want is in GETUser.js.
// We need to create our own proxy that will handle this for us
Ext.define('AjaxGet', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.ajaxGet',
// Per your requirement, we want to send individual requests
batchActions: false,
createOperation: function (action, config) {
// This means we're doing an action against one of our records
if (config && config.records) {
if (action === 'destroy') {
config.params = config.records[0].getDeleteParams();
} else if (action === 'create' || action === 'update') {
config.params = config.records[0].getUpsertParams();
}
}
return this.callParent(arguments);
}
});
// This is the desired, "GET" User model that uses GETs and query params for all actions
Ext.define('GETUser', {
extend: 'Ext.data.Model',
idProperty: 'Id',
fields: [{
name: 'Name',
type: 'string'
}, {
name: 'Id',
type: 'int'
}, {
name: 'Age',
type: 'int'
}, {
name: 'Sex',
type: 'string'
}],
proxy: {
type: 'ajaxGet',
api: {
read: 'Users',
create: 'upsertuser',
update: 'upsertuser',
destroy: 'removeuser'
},
actionMethods: {
create: 'GET',
update: 'GET',
destroy: 'GET'
}
},
getUpsertParams: function () {
const data = this.getData();
// Means this record hasn't been saved, so we're in the CREATE state
if (this.phantom) {
// We don't want to send the ID with what the framework sets as the ID
data.Id = undefined;
}
return data;
},
getDeleteParams: function () {
return {
Id: this.get('Id')
};
}
});
So what I ended up doing was creating a custom proxy that overrides the createOperation method to check which operation we're doing... based on that operation, we use the methods in the model to retrieve the params we want to send to the API. You need actionMethods in the proxy because otherwise, they default to POSTs.
I'm completely new to Extjs. I'm trying to get data using proxy like in this guide but I still don't understand it. The code is written like this.
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['id', 'name', 'email']
});
//The Store contains the AjaxProxy as an inline configuration
var store = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'ajax',
url : 'users.json'
}
});
store.load();
My question is very basic. Is this code written in the same file, in my case, (root)/app/view/user.js or should I put it in different file? And how to do it if it is in separated file. Fyi, I got error when I put it in the same file.
In ExtJs have store proxy and also Ajax request you can use both.
Proxies are used by Ext.data.Store to handle the loading and saving of Ext.data.Model data. Usually developers will not need to create or interact with proxies directly.
Ajax singleton instance of an Ext.data.Connection. This class is used to communicate with your server side code.
I have created and Sencha Fiddle demo. Here I have create 2 local json file (user.json & user1.json).
I am fetching data using store proxy(from user.json) and Ext.ajax request(from user1.json).
Hope this will help you to solve your problem.
*Note this will work for both modern and classic.
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['name', 'email', 'phone']
});
Ext.create('Ext.data.Store', {
storeId: 'userStore',
model: 'User',
proxy: {
type: 'ajax',
url: 'user.json',
reader: {
dataType: 'json',
rootProperty: 'data'
}
}
});
Ext.create('Ext.panel.Panel', {
width: '100%',
renderTo: Ext.getBody(),
padding: 15,
items: [{
xtype: 'button',
margin:5,
text: 'Get Data using Store Load',
handler: function () {
var gridStore = this.up().down('#grid1').getStore();
gridStore.load(function () {
Ext.Msg.alert('Success', 'You have get data from user.json using store.load() method..!');
});
}
}, {
xtype: 'grid',
itemId:'grid1',
title: 'User Data Table1',
store: Ext.data.StoreManager.lookup('userStore'),
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Email',
dataIndex: 'email',
flex: 1
}, {
text: 'Phone',
dataIndex: 'phone'
}],
height: 200,
width: '100%',
}, {
xtype: 'button',
margin:5,
text: 'Get Data using Ajax request',
handler: function () {
var me = this.up(),
gridStore = me.down('#grid2').getStore();
me.down('#grid2').mask('Pleas wait..');
Ext.Ajax.request({
url: 'user1.json',
method: 'GET',
success: function (response) {
me.down('#grid2').unmask();
var data = Ext.decode(response.responseText);
gridStore.loadData(data.data);
Ext.Msg.alert('Success', 'You have get data from user1.json using Ext.Ajax.request method..!');
},
failure: function (response) {
me.down('#grid2').unmask();
//put your failure login here.
}
});
}
}, {
xtype: 'grid',
itemId: 'grid2',
title: 'User Data table2',
store: Ext.create('Ext.data.Store', {
fields: ['name', 'email', 'phone']
}),
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Email',
dataIndex: 'email',
flex: 1
}, {
text: 'Phone',
dataIndex: 'phone'
}],
height: 200,
width: '100%',
}]
});
Please read the points below to understand this. This link on architecture would be helpful.
a. Since you are have created a Universal application, it means you are using Ext JS 6 or above. For this, the folder structure of CMD generated app is as follows:
app
model
store
view
classic
src
view
modern
src
view
b. The app folder is for classes shared by the classic and modern views. This will typically be model definitions in app/model, and shared controllers and view models in app/view folders.
c. Code in classic folder can reference classes in app folder, but can not reference code in modern folder. Similarly, code in modern folder can reference classes in app folder, but can not reference code in classic folder. (It means the model, store, viewmodel and viewcontroller classes in modern and classic apps can extend these classes from the app folder.)
d. Best practice is to declare store in a viewmodel but if the store config is complex, then define its class in the store folder.
e.To declare store in a viewmodel of classic app, example is given below. Similarly you will do for the modern app also.
//MyApp/classic/src/view/main/MainModel.js
stores: {
articles: {
model: 'MyApp.model.MyModel',// in classic/src/model folder
autoLoad: true,
proxy: {
type: 'ajax',//if it's cross-domain, use jsonp
url : 'users.json',
reader: {
type: 'json', //this is default
rootProperty: 'data'//the location in data feed from where you want to start reading the data
}
}
}
}
Now bind this store in the view. For example, in a grid:
{
xtype: 'grid',
bind: {
store: '{articles}'
}
//More code
}
f. If store is defined in a class (e.g.classic/src/store/Articles.js), then declare in a viewmodel like this. Binding will be same as above.
//MyApp/classic/src/view/main/MainModel.js
stores: {
articles: {
type: 'mystore' //this is alias of store class.
model: 'MyApp.model.MyModel', //in classic/src/model folder
}
}
Hope this solves your problem.
I'm working with ExtJs 6.2.0 and Java Spring MVC for the REST API.
I'm trying to delete an object from one of my store but I'm having a problem : instead of using my id named idCamp, extjs is using the field named id that contains an extjs generated id (for example: extModel47-1).
I'm working on the delete part but I didn't try to update a camp nor fetch one, but I think the configuration is the same for these three operations that need the id.
Here is my store:
Ext.define('XXXXXX.store.Camps', {
extend: 'Ext.data.Store',
alias: 'store.camps',
model: 'XXXXXX.model.Camp',
fields: [
'idCamp', // More irrelevant fields
],
autoLoad : true,
autoSync: true,
storeId: 'storeCamp',
proxy: {
type: 'rest',
idParam: 'idCamp',
url: // irrelevant,
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json'
}
}
});
Here is my model:
Ext.define('XXXXXX.model.Camp', {
extend: 'Ext.data.Model',
idProperty: 'idCamp',
fields: [
{ name: 'idCamp', type: 'int' },
// More irrelevant fields
]
});
I also tried to put an idProperty inside the writer/reader inside the proxy but it didn't do anything.
Forgive my poor usage of the English language since I'm a French people.
Best regards,
Morony
The issue is using a combination of fields/model in your store definition. They are in competition with each other. Remove the fields definition.
I have the next store:
Ext.define('Invoices.store.Invoice', {
extend: 'Ext.data.Store',
model: 'Invoices.model.Invoice',
alias: 'store.InvoiceStore',
remoteFilter: false,
proxy: {
type: 'ajax',
url: '/invoices/filter',
reader: {
type: 'json'
}
},
autoLoad: false
});
and this model:
Ext.define('Invoices.model.Invoice', {
extend: 'Ext.data.Model',
fields: ['data']
});
When I call this compnent from a view, the error shown:
{
xtype: 'searchfield',
name: 'client',
store: 'InvoiceStore',
fieldLabel: 'Cliente<b><span style="color: #d32f2f">*</span></b>'
},
Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
And this happen in the next line of code from SearchField component main class:
if (!me.store.proxy.hasOwnProperty('filterParam')) {
me.store.proxy.filterParam = me.paramName;
}
I supposed it happens because of null reference passed to the component, maybe the store, but I changed the alias and the model and nothing happen yet, the same error is still shown.
Any help? Any Idea? Do I deserve to be fired?
As far as I can tell you aren't creating the store instance anywhere. If you're just passing a string, it means it's the id of an already existing store. If you want to create the store by alias (which is what I think you're trying to do), then you need to specify it like so:
store: {
type: 'InvoiceStore'
}
I am creating a mobile application with Sencha Touch 2 that would load its views dinamically depending on a Json response from the server.
It means that before the load of the view I have to compose the view with some generic elements. For example, if I receive a Json string from the server corresponding to a List view I would have to dinamically fill the list items (name, url, descriprion) with a store and a proxy.
This works, but then I would like to select some item on that list and load another list, but this time I want to change the proxy. My new proxy is the url field from the selected item. I get the url field from the selected item and change the proxy, but this introduces a problem:
I am using an Ext.navigation.View, and I want to maintain navigation history. In the above case, if I go back in the navigation history the items on the first list change to the items on the last list.
I am searching for some kind of workflow to achieve dynamic load of the views depending on independent data for each one, and always maintaining the MVC-Store pattern and the navigation history.
This is my model for the list item:
Ext.define('ExampleApp.model.ListItem', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'url', 'descriprion']
}
}
This is the store for the List:
Ext.define('ExampleApp.store.ListItems', {
extend: 'Ext.data.Store',
config: {
autoLoad: false,
model: 'ExampleApp.model.ListItem',
proxy: {
type: 'jsonp'
url: 'http://mydomain.com/myjsonresponse',
reader: {
type: 'json',
useSimpleAccessors: true
}
}
}
})
This is my view:
Ext.define('ExampleApp.view.MyList', {
extend: 'Ext.List',
xtype: 'mylist',
requires: ['ExampleApp.store.ListItems'],
config: {
title: 'My List',
itemTpl: '{name} - {description}',
store: 'ListItems'
}
})
This is the function called on the itemtap event of my list:
listItemTapped: function (view, index, target, record, event) {
var listItems = Ext.getStore('ListItems');
listItems.getProxy().setUrl(record.get('url'));
listItems.load();
this.getMain().push({
xtype: mylist
});
}
What you can try is creating separate store for each list instead of reusing existing one.
listItemTapped: function (view, index, target, record, event) {
var listItems = Ext.create('ExampleApp.store.ListItems', {newUrl : record.get('url')});
listItems.load();
this.getMain().push({
xtype: mylist,
store: listItems
});
}
and add initialize function to use newUrl:
Ext.define('ExampleApp.store.ListItems', {
extend: 'Ext.data.Store',
config: {
autoLoad: false,
newUrl : null,
model: 'ExampleApp.model.ListItem'
},
initialize : function() {
this.setProxy({
type: 'jsonp'
url: this.config.newUrl,
reader: {
type: 'json',
useSimpleAccessors: true
}
});
}
})
You may want to destroy these stores once their view is popped.
#ThinkFloyd, agree that we need to destroy the store when we leave the view, as it will create a problem later when application has many views and has larger stores with lots of data. I recently face the same issue and this helps me a lot...thanks