Model with associations, 1 request fill 2 components best practice - sencha-touch

What would be the best practice or design approach for the following scenario:
There is a json been returned from the server that has information about people and their addresses
I need to show a form with the general information of the person plus a list with every address.
In this list it is mandatory that each address is an item of the list because it will be multiselect true in order to do something else.
What I have done is:
a)define a model "Persona" with a hasMany relation to "Direccion"(spanish for address), my proxy is here in the model
b)define a model "Direccion"
c)define a list and try to play with the itemTpl config in order to display 1 address per itemList but so far I can only display all the addresses for a given person in the same itemList.
Is there a way to achieve this ?
Is this approach good given this scenario?
I was trying to do only 1 request and have only 1 store to fill out this 2 components but now I'm having doubts about it.
So what would be the best design/practice given this scenario?
JSON response
{
"personas": [
{
"id": 1,
"nombre": "jon",
"apellido": "caballero",
"direcciones": [
{
"direccionId": 1,
"calle": "fco villa",
"colonia": "barona"
},
{
"direccionId": 2,
"calle": "duraznos",
"colonia": "canutillo"
}
]
}
]
}
Models
Ext.define('Associations.model.Direccion', {
extend: 'Ext.data.Model',
config: {
idProperty: 'direccionId',
fields: [
{ name: 'calle', type: 'auto' },
{ name: 'colonia', type: 'auto' }
]
}
});
Ext.define('Associations.model.Persona', {
extend: 'Ext.data.Model',
requires: ['Associations.model.Direccion'],
config: {
fields: [
{ name: 'nombre', type: 'auto' },
{ name: 'apellido', type: 'auto' },
],
hasMany:[
{
foreignKey: 'direccionId',
associationKey: 'direcciones',
name: 'direcciones',
model: 'Associations.model.Direccion'
}
],
proxy: {
type:'ajax',
url: 'data/respuesta.json',
reader: {
type:'json',
rootProperty:'personas'
}
}
}
});
Store
Ext.define('Associations.store.Persona', {
extend: 'Ext.data.Store',
requires: [
'Associations.model.Persona'
],
config: {
model: 'Associations.model.Persona',
autoLoad: true
}
});
List
Ext.define('Associations.view.PersonaList', {
extend: 'Ext.List',
xtype: 'personalist',
config: {
onItemDisclosure: true,
emptyText: 'No se encontraron personas',
store: 'Persona',
padding: 10,
margin: 10,
itemTpl : [
'<tpl for="direcciones">',
'<li>Colonia {colonia}</li>',
'<li>Calle {calle}</li>',
'</tpl>',
].join('')
}
});
Any ideas?
Thanks in advance.

When you do model.load() and the model has a hasMany relation to another model a store for the child objects is autogenerated therefore the best approach would be to load the model get the store of the child records and set it to the list.

Related

How to set dynamic url in sencha touch using store?

I am new for this platform, Now i am unable to set dyanimic url using category id and token.
What i want:
I have list different items, which have different ids but same token, token(tokent is same one user) getting from login phase. I want to get value accorading to category id from the server.
Here is the my model:
Ext.define('MyApp.model.CategoryDisplayModelMenu', {
extend: 'Ext.data.Model',
config: {
fields: [
/*'cat_id',*/
'category',
'name',
],
belongsTo: "MyApp.model.CategoryDisplayModel"
}
});
and another related model is:
Ext.define('MyApp.model.CategoryDisplayModel', {
extend: 'Ext.data.Model',
requires: ['MyApp.model.CategoryDisplayModelMenu'],
config: {
fields: [
{name:'data', mapping: 'data'},
{name:'name'},
{name: 'category'},
{name: 'author'},
],
}
});
What i am set in store, but could not work:
Ext.define('MyApp.store.CategoryValueStore', {
extend: 'Ext.data.Store',
alias: 'store.CategoryValueStore',
requires: [
'MyApp.model.CategoryDisplayModel'
],
config: {
model: 'MyApp.model.CategoryDisplayModel',
storeId: 'categoriesvaluestore',
proxy: {
type: 'rest',
url: 'http://horror/myapp/api/word/searched_words/catID/'+ 1+'/'+ SDSILLYTOKEN+'/'+650773253e7f157a93c53d47a866204dedc7c363,
noCache: false,
reader: {
type: 'json',
rootProperty: ''
} } }
});
How to set above url, dynamic, cat id and token may be differnt.
But it works when i set these in store
Ext.define('MyApp.store.ArchitectureDisplayStore',{
extend: 'Ext.data.Store',
requires:[
'MyApp.view.Main'
],
config:
{
model: 'MyApp.model.CategoryDisplayModel',
autoLoad:true,
id:'Category',
proxy:
{
type: 'ajax',
url : 'http://horror/myapp/api/word/searched_words/catID/1/SDSILLYTOKEN/650773253e7f157a93c53d47a866204dedc7c363', // file containing json data
reader:
{
rootProperty:''
} } }
});
In View , I set getting value on list like this:
Ext.define("MyApp.view.ArchitectureDisplayMain", {
extend: 'Ext.Container',
alias: "widget.architecturewords",
config: {
{
xtype: 'list',
scrollable: true,
itemId: 'demolist',
itemTpl: [
'<div><tpl for="data"><ul class="catList">{name} -test- {category}</ul> <ul>{author}</ul></tpl></div>'
],
store: 'categoriesvaluestore',
}
}
});
My category display model:
Ext.define('MyApp.model.CategoryModelMenu', {
extend: 'Ext.data.Model',
config: {
fields: [
'cat_id',
'category_name',
],
belongsTo: "MyApp.model.CategoryModel"
}
});
and
Ext.define('MyApp.model.CategoryModel', {
extend: 'Ext.data.Model',
requires: ['MyApp.model.CategoryModelMenu'],
config: {
fields: [
{name:'data', mapping: 'data'},
{name: 'cat_id'},
{name: 'category_name'},
],
}
});
EDIT:
Ext.define('MyApp.view.Category', {
extend: 'Ext.List',
alias: "widget.category",
config: {
title: 'Stores',
cls: 'category-data',
scrollable: false,
store: 'CategoryStore',
itemTpl: [
'<div class="categoryListings">',
'<tpl for="data">',
'<span onClick="catOption({cat_id})">{category_name}</span> ',
'</tpl>',
'</div>',
].join('')
}
//}
});
function catOption(id){
console.log("ID--"+id);
var tokan= '650773253e7f157a93c53d47a866204dedc7c363';
Ext.Viewport.remove(Ext.Viewport.getActiveItem(), true);
Ext.Viewport.add([
{ xtype: 'wordsview' }
]);
} and others
In wordsview, I like to display respective words of clicked category.
It is ok, when click this, first item of id p1, it shows next view.
Please tell me, How to get dynamic data accorading to its category id and token. please give some solution.Thank you advance.
If i understood you correctly
Let's say if you have category id and token in localStorage.
You can do like this
proxy:
{
type: 'ajax',
url : 'http://horror/myapp/api/word/searched_words/catID/'+localStorage.catId+'/SDSILLYTOKEN/'+localStorage.token,
reader:{
rootProperty:''
}
}
OR
Do as #Alex posted. That is better way.. Like
function catOption(id){
console.log("ID--"+id);
var token= '650773253e7f157a93c53d47a866204dedc7c363';
var url = 'http://horror/myapp/api/word/searched_words/catID/'+id+'/SDSILLYTOKEN/'+token;
Ext.getStore("categoriesvaluestore").getProxy().setUrl(url);
Ext.getStore("categoriesvaluestore").load();
Ext.Viewport.remove(Ext.Viewport.getActiveItem(), true);
Ext.Viewport.add({ xtype: 'wordsview' });
}
When accessing your Store from your View or anywhere else, you can dinamically change the Url this way:
var stProxy = Ext.StoreMgr.get("myStore").getProxy();
stProxy.setUrl("http://the.new.url");
Ext.StoreMgr.set("myStore").setProxy(stProxy);
--
The particular problem in your scenario is that you may have to populate your list manually. If you want a List to include the result of calling the same Store with different URLs, I suggest to build a new local Store loading the content of all iterations. Then make the List "store" property be this global Store.

Generate items in Ext.dataview.List from hasMany models the MVC way

I have a Blog model with hasMany Posts (and many other fields). Now I want to list these posts in a List-view like that:
[My post #1]
[My post #2]
[My post #3]
As far as the API described, I'm able to pass either a store or a data attribute to Ext.dataview.List. But I was not able to find out how to pass the hasMany records to the list so it will display an item for each of them.
Do I really have to create another store? Isn't it possible to configure my dataview to something like store: 'Blog.posts' or data: 'Blog.posts' or even records: 'Blog.posts'?
Extend the dataview.List to define the itemtpl to loop through the posts
itemTpl: new Ext.XTemplate(
'<tpl for="**posts**" >',
'<div>{TheBlogPost}</div>',
'</tpl>'
)
As #Adam Marshall said, this doesn't work as easy as I imagined.
Sencha autogenerates stores from associations if you know how to access them.
So you simply can switch out the list's store for the autogenerated "substore" when it has loaded.
This approach probably has some problems, e.g. when listpaging plugin is used, but it is quick.
Example:
MODELS
Ext.define('Conversation', {
extend: 'Ext.data.Model',
config: {
fields: [
],
associations:
[
{
type: 'hasMany',
model: "Message",
name: "messages",
associationKey: 'messages'
}
]
}
});
Ext.define('Message' ,
{
extend: "Ext.data.Model",
config: {
idProperty: 'id_message',
fields: [
{ name: 'text', type: 'string' },
{ name: 'date', type: 'string' },
{ name: 'id_message', type: 'int' },
{ name: 'me', type: 'int'} // actually boolean
]
}
}
);
JSON
[
{
"messages": [
{"id_message": 11761, "date": 1378033041, "me": 1, "text": "iiii"},
{"id_message": 11762, "date": 1378044866, "me": 1, "text": "hallo"}
]}
]
CONTROLLER
this.getList().getStore().load(
{
callback: function(records, operation, success) {
//IMPORTANT LINE HERE:
getList().setStore(Ext.getStore(me.getList().baseStore).getAt(0).messages());
},
scope: this
}
);
LIST-VIEW
{
flex: 1,
xtype: 'list',
itemId: 'ConversationList',
data: [],
store: 'ConversationStore',
baseStore: 'ConversationStore',
itemTpl:
' {[app.util.Helpers.DateFromTimestamp(values.date)]}<br><b>{name}</b>' +
' {[app.util.Helpers.fixResidualHtml(values.text)]} </div>' +
},

Adding a AJAX response data to a store

How to add a data to a json store if my data is coming from a back end AJAX call.
my store is as follows .
Ext.define('MyApp.store.GeographyMasterStore', { extend: 'Ext.data.Store',
requires: [
'MyApp.model.GeographyMasterModel'
],
config: {
model: 'MyApp.model.GeographyMasterModel',
storeId: 'geographyMasterStore',
proxy: {
type: 'ajax',
reader: {
type: 'json'
}
}
}
});
And my model is as follows:
Ext.define('MyApp.model.GeographyMasterModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'Code'
},
{
name: 'Description'
},
{
name: 'Level_Code',
mapping: 'Level Code'
},
{
name: 'Name'
}
]
}
});
If I add the data like this
var geographyMasterStore = Ext.getStore('geographyMasterStore');
geographyMasterStore.add(<data from backend AJAX call>);
it does not show me the mapped field i.e. Level_Code
Usually I when add a record to the store like this :
Ext.create('App.model.MyModel', JSON.parse(response.responseText);
Where response is the response from an Ext.Ajax.request
Hope this helps
You need create a model:
var record = Ext.create('model.GeographyMasterModel', Ext.JSON.decode(response.responseText));
save the model:
record.save()
reload the store:
geographyMasterStore.load()

Populating Combobox from remote server

I have a combobox, i need to populate data from the server. In the server side i have the following data to be displayed.
PersonID
PersonFName
PersonLName
In the combobox, i need to display the text as PersonFName + PersonLName (Like James Smith- This is what it will display in the drop down) , and when a user selects a record, I need to display the corresponding PersonID (Like Person with PersonFName and PersonLName has the PersonID of 1) of that user.
I am unable to figure this out, here's my code
View :
{
xtype: 'combobox',
id: 'personcombo',
readOnly: false,
selectOnFocus: true,
forceSelection: true,
store: 'Person'
}
Store :
Ext.define('MyApp.store.PersonStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.Person'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
model: 'MyApp.model.Person',
proxy: {
type: 'ajax',
api: {
read: 'person.php',
create: 'person.php'
},
reader: {
type: 'array'
}
}
}, cfg)]);
}
});
Model :
Ext.define('MyApp.model.Person', {
extend: 'Ext.data.Model',
fields: [
{
name: 'PersonID'
},
{
name: 'PersonFName'
},
{
name: 'PersonLName'
}
]
});
I think your question is: how to display PersonFName + PersonLName in the combobox but keep the PersonID field as the value.
You should add a converted field which joins the first and last names in your data model and then make that one your combobox displayField config.
Though the other answer did bring up a good point that the defined store in your combo is Person but you are showing code for a store named PersonStore.
It would look something like this:
Model:
Ext.define('MyApp.model.Person', {
extend: 'Ext.data.Model',
fields: [
{
name: 'PersonID'
},
{
name: 'PersonFName'
},
{
name: 'PersonLName'
},
{
name: 'PersonName',
convert: function(value, record) {
return record.data.PersonFName + ' ' +
record.data.PersonLName;
}
}
]
});
Store:
// changed to "Person" instead of "PersonStore"
Ext.define('MyApp.store.Person', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.Person'
],
model: 'MyApp.model.Person',
proxy: {
type: 'ajax',
api: {
read: 'person.php',
create: 'person.php'
},
reader: 'array'
}
});
View:
{
xtype: 'combobox',
id: 'personcombo',
readOnly: false,
selectOnFocus: true,
forceSelection: true,
store: 'Person',
valueField: 'PersonID',
displayField: 'PersonName' // the converted field
}
Your combobox has 'Person' as the store, but I don't see you create a store called Person anywhere. Try store: Ext.create('MyApp.store.PersonStore', {autoLoad: true}).
You can also simplify your store:
Ext.define('MyApp.store.PersonStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.Person'
],
model: 'MyApp.model.Person',
proxy: {
type: 'ajax',
api: {
read: 'person.php',
create: 'person.php'
},
reader: 'array'
}
});

Saving Model with hasOne association

I've got these models :
Ext.define('TestApp.model.User', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'username', type: 'string'},
],
proxy: {
type: 'localstorage',
},
},
});
Ext.define('TestApp.model.Config', {
extend: 'Ext.data.Model',
config: {
hasOne : {model: 'TestApp.model.User', name: 'user'},
proxy: {
type: 'localstorage',
},
}
});
I've tried to save a config entry like this :
var david = Ext.create('TestApp.model.User', {username: 'david'})
david.save();
var config = Ext.create('TestApp.model.Config');
config.setUser(david);
config.save();
When I restart the application, I have my user entry saved and my config entry saved but, my association is not saved:
config.getUser() -> I get undefined
According to Mitchell Simoens storing associated data isn't supported.
Unsure if it helps in your case, but an approach is sketched (that approach also seems to adress my own current (unrelated) problem).
Hope it helps