How to make a model for a json array in extjs? - javascript

The data I'm getting back from my server looks like:
["admin", "user", "developer", "super"]
And I'm trying to map that into this model:
Ext.define('RoleModel', {
extend: 'Ext.data.Model',
//fields: [{}]
});
My store looks like this:
Ext.create('Ext.data.Store', {
model: 'RoleModel',
proxy: {
type: 'ajax',
url : '/roles',
reader: {
type: 'json'
}
},
autoLoad: true
});
How can I map the single array I'm getting from the server into my RoleModel?

You already got it, before your JSON can be parsed into your data model it needs to be in the form:
[
{ "role": "admin" },
{ "role": "user" },
{ "role": "developer" },
{ "role": "super" }
]
... but if you're rocking ExtJS 5.x you don't need to manually make the Ajax call - you can apply a transform on the proxy's reader, for example:
Ext.create('Ext.data.Store', {
model: 'RoleModel',
proxy: {
type: 'ajax',
url : '/roles',
reader: {
type: 'json',
transform: function(data) {
return data.map(function(x){
return { role: x };
});
}
}
}
});
ยป Fiddle

I ended up adding a role field to my model and doing something like:
Ext.Ajax.request({
url: '/roles',
success: function(response){
var json = Ext.JSON.decode(response.responseText);
var jsonObj = json.map(function(r){ return {role: r}});
store.loadData(jsonObj);
}
});

Related

How to create parameterized Ext Rest Proxy on my Ext Store

I have a API that sends out a paginated result of data and I want it to be consumed my Ext JS app but I don't know how to supply the needed parameters.
Here is the response I expect:
{
"currentPage": 1,
"from": 1,
"items": [
{
"id": 1,
"customer": "Customer 1",
"movie": "Movie 1",
"dateRented": "2021-01-25T01:22:42.143",
"dateReturned": "2021-01-25T01:22:50.447"
},
{
"id": 2,
"customer": "Customer 2",
"movie": "Movie 2",
"dateRented": "2021-01-25T01:22:42.15",
"dateReturned": "2021-01-25T01:22:54.573"
}
],
"pageSize": 2,
"to": 2,
"totalCount": 1000003,
"totalPages": 500002,
"hasPreviousPage": false,
"hasNextPage": true
}
Here is the endpoint:
/api/Rentals/{currentPage}/{pageSize}
Here is my Ext store but I don't know how I will be able to pass the value for currentPage and pageSize:
Ext.define('Vidly.store.PagedRentals', {
extend: 'Ext.data.Store',
alias: 'store.pagedrentals',
storeId: 'pagedrentals',
model: 'Vidly.model.PagedRental',
autoLoad: true,
autoSync: true,
proxy: {
type: 'rest',
url: 'https://localhost:44313/api/Rentals/',
useDefaultXhrHeader: false,
reader: {
type: 'json',
headers: { 'Accept': 'application/json' },
},
writer: {
type: 'json',
writeAllFields: true
}
},
});
And here is the model:
Ext.define('Vidly.model.PagedRental', {
extend: 'Ext.data.Model',
fields: [
{ name: 'currentPage', type: 'int' },
{ name: 'from', type: 'int' },
{ name: 'to', type: 'int' },
{ name: 'pageSize', type: 'int' },
{ name: 'totalCount', type: 'int' },
{ name: 'totalPages', type: 'int' },
],
hasMany: 'Rental',
});
I hope someone can help me with my problem. Thank you.
Ext's rest proxy is designed to use standard REST APIs where paging and filtering options are passed in as query parameters. I.e. something like
https://localhost:44313/api/Rentals?start=1&limit=25
I would recommend to use this approach rather than a non standard REST API. It will enable you to use Ext's related features seamlessly.
If there is no way to change the API and you need to stick with your current server configuration then you need to create a custom proxy overriding some of the related functions. The best bet if you override the buildUrl function and pass your custom generated URL to the request object.
UPDATE
You can start with this code (also created a Fiddle):
Ext.define('Yournamespace.proxy.custom', {
extend: 'Ext.data.proxy.Rest',
alias: 'proxy.custom',
buildUrl: function(request) {
const url = this.callParent([request]);
const operation = request.getOperation();
console.log(url, this.getParams(operation))
return url;
}
});
Ext.define('User', {
extend: 'Ext.data.Model',
});
Ext.application({
name : 'Fiddle',
launch : function() {
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
pageSize: 10,
proxy: {
type: 'custom',
url: 'https://localhost:44313/api/Rentals/',
reader: {
type: 'json',
rootProperty: 'users'
}
},
autoLoad: true
});
}
});
You can write your custom code to the buildUrl function. Currently only the default URL and the params are collected and logged there but it does the default stuff. You can tweak the URL here and return the new URL at the end.

How to render Kendo UI grid from AJAX response data?

I have this code that gets json object from a static url and then renders grid. But I want to use json data retrived as AJAX response and then render grid using this response text. Because for practical deployment I can't use static URL.
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {url: "http://url/returnsjsonobject.php"}
//THIS GETS DATA FROM STATIC URL BUT I WANT TO READ DATA AS AJAX RESPONSE
//like read: somefunctioncall
//or like read: somevariable
},
schema: {
model: {
fields: {
id: {type: "string", editable: false},
name: {type: "string"}
}
}
},
pageSize: 20
},
height: 430
columns: [
{field: "id", title: "ID", width: "20px", hidden: "true"},
"name",
});
Thanks in advance for help and if you have any alternative method; I will be happy to try it.
Remember that transport.read.url does not have to be a constant but might be a function:
transport: {
read: {
url: function(options) {
return "somefunctionalcall?id=" + options.id,
},
dataType: "json"
}
or even define transport.read as a function:
transport: {
read: function (options) {
$.ajax({
dataType: "json",
url: "somefunctionalcall",
success: function (d) {
options.success(d);
}
});
}
}

How to create a generic ExtJS combo box store?

I want to create a generic Extjs store for combo boxes.
The store should be able to:
Take a URL
Read data using a proxy from the server
Should work for any model
How can I achieve this?
This is what I have for start:
Ext.create('Ext.data.Store', {
proxy: {
type: 'ajax',
url: rawURL,
reader: {
type: 'json'
}
}
})
Using ExtJS 4.1
function getGenericStore(storeURL, valField, dispField) {
var modelName = 'Model' + me.id;
var model = Ext.define(modelName, {
extend: 'Ext.data.Model',
fields: [
{name: valField, type: 'string'},
{name: dispField, type: 'string'}
]
});
return Ext.create('Ext.data.Store', {
proxy: {
type: 'ajax',
model: model,
url: storeURL,
reader: {
type: 'json',
read: function(response) {
var json = Ext.decode(response.responseText);
var records = [];
Ext.each(json, function(item) {
var record = Ext.create(modelName);
record.set(val, item[val]);
record.set(display, item[display]);
records.push(record);
});
return {
success: true,
total: json.length,
count: records.length,
loaded: true,
records: records
};
}
}
}
});
}

Sencha Store proxy is not getting called

I want to load store data dynamically and don't want to use model for this. if I provide data list gets populated but if I use store's proxy it doesn't get called and url is not getting hit. Please help.
Ext.define('TrainEnquiry.view.SearchTrainResults', {
extend: 'Ext.List',
xtype: 'searchedtrainresult',
requires: 'Ext.data.proxy.JsonP',
config: {
itemId: 'searchedtrainresult',
title: 'Train Result:',
itemTpl: '<div class="myContent">'+
'<div><b>{number}</b> </div>' +
'</div>',
store: {
fields: ['number'],
/*data: [
{number: 'Cowper'},
{number: 'Everett'},
{number: 'University'},
{number: 'Forest'}
]*/
proxy: {
url: 'http://abc.amazonaws.com/search.json',
type:'jsonp',
extraParams : {
'q' : '12313'
},
reader: {
type: 'json',
},
success: function() {
debugger;
console.log('success');
},
failure: function() {
debugger;
console.log('failure');
}
}
},
onItemDisclosure: true
}
});
I think your "fields" config option needs to be a proper Ext.data.Field object, so maybe this would work:
Ext.define('TrainEnquiry.view.SearchTrainResults', {
...
config: {
...
store: {
fields: [ { name: 'number', type: 'string'} ],
proxy: {
...
}
},
...
}
});
(Reference from Sencha forums)
You could try removing the pageParam and startParam from your proxy. Just like this
Ext.create('Ext.data.Store', {
storeId:'UserStore',
autoLoad: true,
model: 'UserModel',
proxy: {
type: 'jsonp', // Because it's a cross-domain
url : 'https://api.twitter.com/1/lists/members.json?owner_screen_name=Sencha&slug=sencha-team&skip_status=true',
reader: {
type: 'json',
root: 'users' // The returned JSON will have array
// of users under a "users" property
},
// Removing pageParam and startParam
pageParam: undefined,
startParam: undefined
}
});
Here is an example http://jsfiddle.net/alexrom7/YNTuN/
Try changing the type of your proxy store to Ajax (type: 'ajax'). Just like this
Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'ajax',
url: '/test.json',
reader: {
type: 'json',
}
},
autoLoad: true
});

ExtJS4 Ext.data.Store Load data from a function

Using ExtJS4 Store, I want to execute a Javascript function to return json data, ie. getMyJsonData, to load the data into the store.
function getMyJsonData() {
var myjson = {... };
return myjson;
}
Trawling through the doco, I can't find a way to define a callback function to load the data, all I found was a Memory Store which loads an already defined data object.
How can I call a function instead ?
Ext.define('perhoo.store.Users',
{
extend: 'Ext.data.Store',
model: 'perhoo.model.User',
autoLoad: true,
data : {
users: [
{ id: 1, name: 'joe44', email: 'joe#joe.com'},
{ id: 2, name: 'bloggs44', email: 'bloggs#joe.com'}
]
},
proxy: {
type: 'memory',
data: this.data,
reader: {
type : 'json',
root : 'users'
}
}
EDIT
The reason I want to call a function is because I want to execute LinkedIn API.
And going through Ext JSONP Proxy (as it's cross domain) makes things 10x more complicated as I have to get LinkedIn auth etc etc (which I don't know how to do it yet)
i.e.
var mydata = null;
function onLinkedInAuth() {
// Linked in api to find connections
IN.API.Connections("me").result( function(result) {
mydata = result;
} );
}
ExtJS4's store using proxy to load data, check below:
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'ajax',
url : '/users.json',
reader: {
type: 'json',
root: 'users'
}
},
autoLoad: true
});
When executed, it reads data from the url, /users.json, and store into itself.
Also, if you want to process data yourself and load them into store yourself, you can check below:
//this is the model we will be using in the store
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'phone', type: 'string', mapping: 'phoneNumber'}
]
});
//this data does not line up to our model fields - the phone field is called phoneNumber
var data = {
users: [
{
id: 1,
name: 'Ed Spencer',
phoneNumber: '555 1234'
},
{
id: 2,
name: 'Abe Elias',
phoneNumber: '666 1234'
}
]
};
//note how we set the 'root' in the reader to match the data structure above
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
model: 'User',
data : data,
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'users'
}
}
});
And you could easily usesetProxy to change the behavior when you want.
Links:
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.AbstractStore-method-setProxy
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.Memory

Categories