extjs 5 associations between two models - javascript

There are two model and connected stores: user and orders in frontend. There are two api calls in backend: getOrder(orderId), and getOrders().
In 'order store' I specified proxy settings for getOrders(). In 'order model' I specified proxy for getOrder(orderId).
When I call user's load method to get associated orders in this case uses model's proxy. Why not use proxy from store? Why it is not using.
P.S.: relation between user and order is descripted in backend and depends on authentication params of user.
User model code
Ext.define('Dev.models.User', {
extend: 'Ext.data.Model',
requires: ['Dev.stores.Orders'],
fields: [
//data
{name: "name", type: "string"},
{name: "userId", type: "string"}
],
proxy: {
type: 'ajax',
url: '/tcc/getmember',
idParam: 'memberId',
reader: {
type: 'json',
idProperty : 'memberId'
}
},
hasMany: {
model: 'Dev.models.Order',
name: 'orders',
storeConfig: {
type: 'orders',
filters: []
}
}
});
Order model code
Ext.define('Dev.models.Order', {
extend: 'Ext.data.Model',
idProperty : 'orderId',
fields: [
{name: "orderId", type: "string"},
{name: "title", type: "string"},
{name: "createMember", type: "string"}
],
proxy: {
type: 'ajax',
api: {
create: '/tcc/setorder',
read: '/tcc/getorder',
update: '/tcc/setorder',
destroy: '/tcc/deleteorder'
},
idParam : 'orderId',
reader: {
type: 'json',
idProperty : 'orderId'
}
},
belongsTo: {
model: "Dev.models.User",
name: 'user',
getterName: 'getUser',
foreignKey: 'userId',
primaryKey: 'createMember'
}
});
Order store code
Ext.define('Dev.stores.Orders', {
extend: 'Ext.data.Store',
model : 'Dev.models.Order',
alias: 'store.orders',
proxy : {
type : 'ajax',
api: {
create: '/tcc/setorder',
read: '/tcc/getorders',
update: '/tcc/setorder',
destroy: '/tcc/deleteorder'
},
reader : {
root: 'orders',
type : 'json',
idProperty : 'orderId'
}
}
});
Sample of usage
function doMemberOne(userId) {
Dev.models.User.load(userId, {
success: function(record, operation) {
console.log("User model was loaded successfully");
doOrders(record.orders());
},
failure: function(record, operation) {
console.log("User model was loaded unsuccessfully");
}
});
}
function doOrders(orderStore) {
orderStore.load({
callback: function(records, operation, success) {
if (success) {
console.log("Orders was loaded successfully");
} else {
console.log("Orders was loaded unsuccessfully");
}
}
});
}
Ext.onReady(function() {
Dev.Authentication.login("admin", "adminpass", "adminorg");
Dev.Authentication.on('login', function(resp) {
console.log("Login is successful.");
doMemberOne(resp.accountid);
});
});

Related

How load data from mySQL to JSON in EXTJS

I create file in my store folder, i want load my data from mySQL to JSon, so this is my code:
Ext.define('DWP3.store.konten.Coba', {
extend: 'Ext.data.Store',
alias: 'store.coba',
uses: [
'Ext.data.Store'
],
initComponent: function(){
var store = Ext.create('Ext.data.Store', {
fields: [
{name: 'periode'},
{name: 'Teknik Informatika S1'},
],
proxy: {
type: 'ajax',
url : 'resources/data/load2.php',
reader: {
type: 'json',
rootProperty: 'view_aktif'
}
},
autoLoad: true
});
}
});
how can i load the data from store?
Can You Help me Please.
It seems better to me declared this way :
Ext.define('DWP3.store.konten.Coba', {
extend: 'Ext.data.Store',
alias: 'store.coba',
fields: [
{name: 'periode'},
{name: 'Teknik Informatika S1'},
],
proxy: {
type: 'ajax',
url : 'resources/data/load2.php',
reader: {
type: 'json',
rootProperty: 'view_aktif'
},
autoLoad: true
});

Kendo UI Scheduler not binding resources properly

I'm having trouble trying to get my KendoUI Scheduler resources to populate correctly. I haven't found a good example of how to bind a nested JSON object (in this case Task and User listed in the screenshot) to resources that are fetched.
Also while running Fiddler, it seems like the resources listed below aren't even fetched from the web service. The documentation is super unclear on some of the specifics and I'm having a hard time finding the problem.
The schedule actually pulls back all the SchedulerEvents (the JSON fetched below) and shows me events bound to the Schedule properly, just they have no resources attached. Right now all of my webservice calls are running off localhost so JSONP shouldn't be required yet as my service calls are all calling "localhost".
I did find something similar to what I'm trying to do with projection of data here via Telerik's documentation, but I haven't been able to figure out a good solution yet.
Edited : updated my question with individual DataSource code
Edited 2 : I should also mention since posting this, the JSON screenshot isn't entirely accurate anymore as I've taken ScheduledTaskId and UserId (the two identifying properties of my Task and User resources I'm trying to add to appointments) and made that property available directly from my SchedulerEvent class to avoid nesting objects.
Javascript
//Datasources code has been moved to here. Explicitly fetching data and assigning to Resources datasource properties
$("#scheduler").kendoScheduler({
date: new Date("#DateTime.Now.ToShortDateString()"),
timezone: "Etc/UTC",
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda"
],
dataSource: {
batch: true,
transport: {
read: {
url: "ServiceURI/Schedule/Get",
dataType: "json"
},
update: {
url: "",
dataType: "json"
},
create: {
url: "",
dataType: "json"
},
destroy: {
url: "",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
resources: [
{
field: "userId",
title: "User",
dataTextField: "displayName",
dataValueField: "userId",
dataSource: userDataSource
}
{
field: "scheduledTaskId",
title: "Task",
dataTextField: "taskName",
dataValueField: "scheduledTaskId",
dataSource: taskDataSource
}
],
schema: {
model: {
id: "shiftId",
fields: {
shiftId: {
from: "ShiftId",
type: "number"
},
title: {
from: "Title",
validation: { required: true }
},
start: {
from: "Start",
type: "date",
validation: { required: true }
},
end: {
from: "End",
type: "date",
validation: { required: true }
},
scheduledTaskId: {
from: "ScheduledTaskId",
type: "number"
},
userId: {
from: "UserId",
type: "number"
},
description: {
from: "Description"
},
recurrenceId: { from: "RecurrenceID" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
}
}
});
Datasources
var userDataSource = new kendo.data.DataSource({
transport: {
read: {
//This should be a customized list of users, or all users fetched from the datastore
url: "ServiceURI/UserProfile/Get/",
dataType: "json"
},
},
schema: {
model: {
id: "userId",
fields: {
userId: {
from: "UserId",
type: "number"
},
displayName: {
from: "DisplayName"
}
}
}
}
});
userDataSource.fetch();
var taskDataSource = new kendo.data.DataSource({
transport: {
read: {
//This should be the entire list of tasks fetched from the datastore
url: "ServiceURI/ScheduledTask/Get?companyId=1",
dataType: "json"
}
},
schema: {
model: {
id: "scheduledTaskId",
fields: {
scheduledTaskId: {
from: "ScheduledTaskId",
type: "number"
},
taskName: {
from: "TaskName"
}
}
}
}
});
taskDataSource.fetch();
JSON returned
Problem
The resources object is inside of the dataSource object as I thought it was supposed to be per the documentation
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda"
],
dataSource: {
resources: [
{
field: "userId",
title: "User",
dataTextField: "displayName",
dataValueField: "userId",
dataSource: userDataSource
}
{
field: "scheduledTaskId",
title: "Task",
dataTextField: "taskName",
dataValueField: "scheduledTaskId",
dataSource: taskDataSource
}
]
}
Answer
Just need to move the resources array outside of the DataSource... works as expected without any explicit .fetch() statements either
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda"
],
resources: [
{
field: "userId",
title: "User",
dataTextField: "displayName",
dataValueField: "userId",
dataSource: userDataSource
}
{
field: "scheduledTaskId",
title: "Task",
dataTextField: "taskName",
dataValueField: "scheduledTaskId",
dataSource: taskDataSource
}
],
dataSource: {
}
DataSource + Scheduler Creation
var userDataSource = new kendo.data.DataSource({
transport: {
read: {
//This should be a customized list of users, or all users fetched from the datastore
url: "ServiceURI/UserProfile/Get/",
dataType: "json"
},
},
requestEnd: function(e) {
//Start Fetching Task Data Source
taskDataSource.fetch();
},
schema: {
model: {
id: "userId",
fields: {
userId: {
from: "UserId",
type: "number"
},
displayName: {
from: "DisplayName"
}
}
}
}
});
Task DataSource declaration.
var taskDataSource = new kendo.data.DataSource({
transport: {
read: {
//This should be the entire list of tasks fetched from the datastore
url: "ServiceURI/ScheduledTask/Get?companyId=1",
dataType: "json"
}
},
requestEnd: function(e) {
//Once Task and User DataSource have been fetched, create the Scheduler
createScheduler(e);
},
schema: {
model: {
id: "scheduledTaskId",
fields: {
scheduledTaskId: {
from: "ScheduledTaskId",
type: "number"
},
taskName: {
from: "TaskName"
}
}
}
}
});
function createScheduler(e){
$("#scheduler").kendoScheduler({
date: new Date("#DateTime.Now.ToShortDateString()"),
timezone: "Etc/UTC",
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda"
],
dataSource: {
batch: true,
transport: {
read: {
url: "ServiceURI/Schedule/Get",
dataType: "json"
},
update: {
url: "",
dataType: "json"
},
create: {
url: "",
dataType: "json"
},
destroy: {
url: "",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
resources: [
{
field: "userId",
title: "User",
dataTextField: "DisplayName",
dataValueField: "UserId",
dataSource: userDataSource
}
{
field: "scheduledTaskId",
title: "Task",
dataTextField: "TaskName",
dataValueField: "ScheduledTaskId",
dataSource: taskDataSource
}
],
schema: {
model: {
id: "shiftId",
fields: {
shiftId: {
from: "ShiftId",
type: "number"
},
title: {
from: "Title",
validation: { required: true }
},
start: {
from: "Start",
type: "date",
validation: { required: true }
},
end: {
from: "End",
type: "date",
validation: { required: true }
},
scheduledTaskId: {
from: "ScheduledTaskId",
type: "number"
},
userId: {
from: "UserId",
type: "number"
},
description: {
from: "Description"
},
recurrenceId: { from: "RecurrenceID" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
}
}
});
}
Start the DataSources fetching from User Source then Task Source and finally creation of the Scheduler.
userDataSource.fetch();
I have never tried this before, but I think above would work as per your requirement.
I think your issue is binding Case. In your Datasources for the resource Objects, you have a model definition, taking items from your JSON data and transforming it into a Model:
var userDataSource = new kendo.data.DataSource({
transport: {
read: {
//This should be a customized list of users, or all users fetched from the datastore
url: "ServiceURI/UserProfile/Get/",
dataType: "json"
},
},
schema: {
model: {
id: "userId",
fields: {
userId: {
from: "UserId",
type: "number"
},
displayName: {
from: "DisplayName"
}
}
}
}
});
In your scheduler Binding, you are setting the dataTextField and dataValueField to:
{
field: "userId",
title: "User",
dataTextField: "DisplayName",
dataValueField: "UserId",
dataSource: userDataSource
}
Notice that your model is displayName and userId, but your resource Bindings are DisplayName and UserId - By the time you are binding into the Scheduler resource collection, the data has been transformed into your model schema, and casing is important.
If you correct the casing, that should solve your issue. You will also need to ensure that both Datasources are populated prior to creating the Scheduler object.

ExtJS 4.2.0 undefined model

I thought I had defined a model for my store, but my console and also my application seem to disagree.
My code looks something like this:
Ext.define("Deeper", {
extend: 'Ext.data.Model',
fields: [{
name: 'ID',
type: 'int'
}, {
name: 'someoneElsesID',
type: 'int'
}, {
name: 'anotherID',
type: 'int'
}],
belongsTo: 'Higher'
});
Ext.define("Higher", {
extend: 'Ext.data.Model',
fields: [{
name: 'name',
type: 'string'
}, {
name: 'status',
type: 'int'
}],
hasMany: {
model: 'Deeper',
name: 'deeper'
}
});
after that, I created the following store:
var store = Ext.create('Ext.data.Store', {
model: 'Higher',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'some/correct/url.json',
reader: {
type: 'json',
root: 'name'
}
}
});
My grid shows inline data correctly, so I tried console.debug(store)
The result is:
model: undefined
and
modelDefaults: null
So where did I go wrong?

Sencha Touch: load store for List using Rest Proxy

I'm new to sencha so I'm sure I'm just missing something simple here. I have a rest service and I need to be able to load my store for my list view.
Here's my model with the proxy:
Ext.define('UserModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'UserId', type: 'int' },
{ name: 'FullName', type: 'string' }
],
proxy: {
type: 'rest',
url: '/rest/user',
reader: {
type: 'json',
root: 'user'
}
}
}
});
And this code works fine for a GET request. So I know that I'm able to talk with my rest service.
var User = Ext.ModelMgr.getModel('UserModel');
User.load(10058, {
success: function (user) {
console.log("Loaded user: " + user.get('UserId') + ", FullName: " + user.get('FullName'));
}
});
My problem is that I'm unable to load data into my list view when adding the proxy code to the store. How do I pass in a parameter to the rest service and load the store?
Ext.define('UserStore', {
extend: 'Ext.data.Store',
config: {
model: 'UserModel',
proxy: {
type: 'rest',
url: '/rest/user',
reader: {
type: 'json',
root: 'user'
},
autoLoad: true
},
sorters: 'FullName',
grouper: function(record) {
return record.get('FullName')[0];
}
}
});
And here's my list view:
Ext.define('UserView', {
extend: 'Ext.List',
xtype: 'userView',
config: {
scrollable: 'vertical',
loadingText: "Loading your social connections . . .",
indexBar: true,
singleSelect: true,
grouped: true,
cls: 'customGroupListHeader',
itemTpl: '{FullName}',
store: 'UserStore',
onItemDisclosure: true
}
});
Haha! I knew it was something simple. The "autoLoad: true" in the store's proxy needs to be outside of the proxy's brackets.
Ext.define('UserStore', {
extend: 'Ext.data.Store',
config: {
model: 'UserModel',
autoLoad: true,

ExtJS4: When to Use Full Namespace VS Just Object Name (Model Associations)

Part of My Item Model:
Ext.define('DnD.model.Item', {
extend: 'Ext.data.Model',
idProperty:'item_number',
associations: [{
type: 'belongsTo',
model: 'Company',
primaryKey: 'id',
foreignKey: 'company_id',
autoLoad: true
}],
proxy: {
type: 'ajax',
url: 'data/items.json',
reader: {
type: 'json',
root: 'items',
idProperty:'id'
}
},
fields: [{
name: 'id',
type: 'int'
},{
name: 'box_number',
type: 'float'
}, {
name: 'item_number',
type: 'float'
}, {
name: 'name',
type: 'string'
},{
name: 'format',
type: 'int'
}, {
name: 'company_id',
type: 'int'
}, {
...
The Company Model
Ext.define('DnD.model.Company', {
extend: 'Ext.data.Model',
associations: [{
type: 'hasMany',
model: 'Item',
primaryKey: 'id',
foreignKey: 'company_id',
autoLoad: true
}],
idProperty:'id',
fields: [{
name: 'id',
type: 'int'
}, {
name: 'name',
type: 'string'
}],
proxy: {
type: 'ajax',
url: 'data/companies.json',
reader: {
successProperty: true,
type: 'json',
root: 'companies',
idProperty:'id'
}
}
})
The app.js file
Ext.Loader.setConfig({
enabled: true,
paths: {
Ext: 'extjs/src',
My: 'app'
}
});
Ext.application({
name: 'DnD',
appFolder: 'app',
autoCreateViewport: false,
controllers: [
'Collections',
'Items'
],
launch: function() {
this.viewport = Ext.create('DnD.view.Viewport', {});
this.viewport.show();
}
});
The Problem
With the code the way it is now, whenever I make a new instance of the item model and attempt to call myItem.getCompany() the console throws an error telling me that the object I created has no such method.
Now, if I change the association to say that an Item belongs to DnD.model.Company (as opposed to just Company), a getter method is created, but it's called getDnD.model.Company() (as opposed to just getCompany()).
From what I can see, it appears that the autoloader can't find the model unless I mention the full path name. However, take a look at my Collection Controller:
Ext.define('DnD.controller.Collections', {
extend: 'Ext.app.Controller',
models: [
'Collection'
],
stores: [
'Collections',
],
views:[
'collection.List'
],
refs: [{
ref: 'collectionList',
selector: 'collectionlist'
}],
init: function() {
}
});
Notice I can reference the models, stores and views without using the full namespace.
Any guidance would be very appreciated.
BelongsTo association has config options "getterName" and "setterName", you can use them to define your own getter and setter method names. Example: {type: 'belongsTo', model: 'My.model.User', foreignKey: 'userId', getterName: 'getUser'}
http://docs.sencha.com/ext-js/4-0/#/api/Ext.data.BelongsToAssociation

Categories

Resources