Nested JSON objects in Sencha Touch store using CakePHP backend API - json

I am using Sencha Touch 1.1 to build a bar locator. I am using CakePHP as my backend API and I want to be able to use the data as Cake outputs it.
Viewing the JSON data below you will see that the Pub data is returned in the 'Pub' array and the Suburb in a similar way. So accessing the data would be done as follows:
Pub.id, Pub.name, Pub.address_1
Does anyone know how I can use this format in my Sencha model and store?
I have my model and store setup as follows:
Ext.regModel('Pub', {
fields: ['id', 'name', 'address_1', 'address_2', 'marker', 'lat', 'lng', 'suburb']
});
Ext.regStore('NearbyStore', {
model: 'Pub',
sorters: 'suburb',
getGroupString: function(record) {
return record.get('suburb');
},
proxy: {
type: 'scripttag',
url: 'http://exampleurl/bars/nearby.json?lat=-55.8874&lng=-11.177',
reader: {
type: 'json',
root: 'results'
}
},
autoLoad: true
});
Below is the JSON data that is returned from my store proxy.
stcCallback1001({"results":[{"Pub":{"id":"125","name":"Brownsville Bowling & Recreation Club","address_1":"31a malouffst","address_2":"-","marker":"default_marker.png","lat":"-33.887402","lng":"151.177002"},"Suburb":{"name":"Knoxville"},"0":{"distance":"0.0002511751890598611"}},{"Pub":{"id":"1721","name":"Hampshire Hotel","address_1":"91 parramatta rd","address_2":"-","marker":"default_marker.png","lat":"-33.886799","lng":"151.177002"},"Suburb":{"name":"Brownsville"},"0":{"distance":"0.06684402352323478"}}]});

you should see
http://docs.sencha.com/touch/1-1/#!/api/Ext.data.Field-cfg-mapping
similar question on stackoverflow :
Accessing nested objects in JSON feed - Sencha Touch
So you should map your model like this :
Ext.regModel('Pub', {
fields: [
{
name: 'id',
type: 'string',
mapping: 'Pub.id'
},
{
name: 'name'
type: 'string',
mapping: 'Pub.name'
},
{
name: 'address_1',
type: 'string',
mapping: 'Pub.address_1'
},
{
name: 'AND SO ON.......'
}
});
Well, I've just started on sencha touch. So I hope im helping.. :)

you will not only have to make these, but also map filtering, remote sorting, success properties, validation errors, and so on. If you are planning a bigger project I would recommend you to switch to Sencha Touch 2 and use Bancha.
Then you will not have to do any of those things. And as a nice bonus you can simply expose your CakePHP models and don't have to write them manually again for Sencha Touch.

Related

Sails.js Can't create data in another model from other model's lifecycle

Hey I'm kinda new to Sails. I've enabled REST api in sails and no I just simply create data using the body of the post request body without the intervention of a controller.
I have defined two models - users, and call_log. Every time an event occurs in my app, I want that to trigger a change in the value of a user in the users table but I also want to create a log in the call log table.
I'm using an afterCreate() lifecycle method and try to use the create() in order to write my data to the second table. I don't seem to get any error, but nothing is written to the dB.
my User.js (model)
module.exports = {
attributes: {
username: {type: 'string', required: true},
country: {type: 'string'},
},
afterCreate: function (valuesToSet, proceed) {
Talk_log.create({
uid: 'myuid',
partner_uid: 'mypartnerid',
action: 'yeahhh'
}).fetch();
valuesToSet.password = 1244;
return proceed();
},
};
my Talk_log.js
module.exports = {
attributes: {
uid: { type: 'string', required: true},
partner_uid: {type: 'string'},
action: {type: 'string'}
},
};
Documentation say "The afterCreate lifecycle callback will only be run on queries that have the fetch meta flag set to true"
So use:
User.create().fetch();
Fetch tell Waterline (and the underlying database adapter) to send back records that were updated/destroyed/created when performing an .update(), .create(), .createEach() or .destroy() query.
U say afterCreate() but in your code is beforeCreate(). Fix that.
I forgot the .then() that handles the bluebird promises and only then I could write to dB.
Talk_log.update({ uid: valuesToSet.uid})
.set({ joined: true})
.fetch()
.then(() => {return proceed();});

Kendo UI Treeview doesn't display date correctly

I am trying to display my json from a mvc controller to be displayed on a checkboxed kendo ui treeview. The code on the asp.net mvc view and the json sent to the view are given below
MyDoc.cshtml code
<script>
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true,
},
dataSource: {
//type: "odata",
transport: {
read: {
url: '#Url.Content("~/Document/GetMyDocs")',
type: "post",
dataType: "json"
}
},
schema: {
model: {
id: "id", text:"Name",
children: "Files"
}
}
},
dataTextField: [ "Name"],
check: onCheck
});
json object
[{"id":1,"Name":"Checking",
"Files":[{"Filename":"doc10","id":"1afd5a4f-086f-44d2-9287-8098384e379e"},
{"Filename":"doc11","id":"89ea3366-14b8-4e91-8273-6e2a51fbe516"}]},
{"id":2,"Name":"Saving",
"Files":[{"Filename":"doc20","id":"c7a88f5d-067e-4f20-93b6-da6eff69d532"},
{"Filename":"doc21","id":"8a0a62ed-1b4a-4e5e-8d59-d57a975a7ab0"}]}]
When I view the page only the toplevel text, "Checking" and "Saving" shows. The date present under Files comes out as undefined.
Thanks
It looks like that Kendo UI uses the dataTextField: [ "Name"] for both the parent and the child node. Since the json in the child data doesn't have a field name equal to "Name" it came out as undefined. Once I changed the property, "FileName" into "Name", it worked. The Telerik's documentation is as atrocious as other third party controls. All their demos are more geared to show how easy peasy it is to create a sexy looking UI using few hard coded data than showing how to create a real world application!

How to access extra parameters in json file in extjs4?

i am working in extjs4 MVC plus yii framework.I am getting stuck at a point which is how to access extra parameters in jason file coming from server and handle it to client side in extjs4.
My code:-
1) My json file is:--
{
'users': [
{
"userId": 1,
"userName": 'Who will win the series11111111?',
"message":"You are welcome",
}
]
}
2) My userModel class in extjs4 :--
In this file there is no any 'message' attribute available.
Ext.define('Balaee.model.sn.UserModel',{
extend: 'Ext.data.Model',
fields: ['userId','userName','password'],
proxy:
{
type:'ajax',
api:
{
read:'http://localhost/balaee/Balaee/index.php?r=SocialNetworking/user/AuthenticateLogin',
create:'http://localhost/balaee/Balaee/index.php?r=SocialNetworking/user/AuthenticateLogin',
},//end of api
reader:
{
type:'json',
root:'users'
},//end of reader
writer:
{
type:'json',
root:'records',
},//End of writer
}//end of proxy
});
3)And here is my view file where I am going to access userName and message fields coming from json file.
Ext.define('Balaee.view...',
{
extend:'Ext.view.View',
store:'kp.UserStore',
config:
{
tpl:'<tpl for=".">'+
'<div id="main">'+
'</br>'+
'<b>userName :-</b> {userName}</br>'+
'<b>message :-</b> {message}</br>'+
'</div>'+
'</tpl>',
itemSelector:'div.main',
}
});// End of login class
But its not working.It display userName field value but not displaying message field value.
Actually I want to access a message field which is not persent in model class in extjs4. Is it correct to access to this type of fields having no any relationship? How can I access this type of fields. Please give me some suggestions.
An Ext.data.Model only knows about the fields it has defined. This is clear from the examples in the documentation.
If you want message to be available to your view, it must also be available from your model:
Ext.define('Balaee.model.sn.UserModel',{
extend: 'Ext.data.Model',
fields: ['userId', 'userName', 'password', 'message'],
// ...
});

Solr live search using ExtJs4

i'm using solr+haystack(django plugin) on the backend and the search is working fine;
While Django(and Haystack) with its templates is doing everything for me(I mean its pretty simple to configure and use), ExtJS4 is a little more complex;
The question is how to use Solr using ExtJS4?
An example is very much appreciated;
Thanks for any help and sorry for my English;
As ExtJS4 is a MVC framework, the solution is done like MVC;
The controller/Search.js
Ext.define('yourapp.controller.Search',{
extend:'Ext.app.Controller',
stores:[
'Searches'
],
views:[
'search.Search',
'search.SearchList'
],
models:[
'Search'
],
init:function(){
this.control({
"search":{
'keyup':this.search,
},
});
},
search:function(inputedTxt, e, eOpts){
this.getSearchesStore().load({
//When sending a request, q will rely to request.POST['q'] on server-side;
//inputedTxt.getValue() -- a value, entered in textfield (or whatever)
params:{
q:inputedTxt.getValue()
},
callback:function(result){
if(result[0]){
//do something with the result
//i'd been creating a window with a grid inside. "Grid"'s view is written below.
}
}
}
});
The models/Search.js
Ext.define('yourapp.model.Search',{
extend:'Ext.data.Model',
fields:[
{name:'name', type:'string'}
]
});
The store/Searches.js
Ext.define('yourapp.store.Searches',{
extend:'Ext.data.Store',
storeId: "searchStore",
model:'yourapp.model.Search',
autoLoad: false,
proxy:{
type:'ajax',
// server-side url
url: '/searchlist/',
actionMethods:{create: "POST", read: "POST", update: "POST", destroy: "POST"},
reader:{
type:'json',
root:'searches'
}
}
});
The view/search/Search.js
//a Text field to input text;
Ext.define('yourapp.view.search.Search',{
extend:'Ext.form.field.Text',
alias: 'widget.search',
id: "searchView",
enableKeyEvents: true,
initComponent:function(){
this.callParent(arguments);
}
});
The view/search/SearchList.js
//a view for a result
Ext.define('yourapp.view.search.SearchList',{
extend: 'Ext.grid.Panel',
alias:'widget.searchlist',
title: 'search result',
store: 'Searches',
columns:[
{
header:'Name',
dataIndex:'name',
flex:1
}
]
});
Somewhere in the view/Viewport.js xtype: 'search', should be inserted for a text field to be displayed.
That's all for a ExtJS4 part.
On server-side -- Django:
'haystack' and Solr should be installed and configured (by 'configured' i mean: search should already work on the server-side);
In someapp/view.py
def searchlist(request):
from haystack.query import SearchQuerySet
# POST["q"] should be receivedt from our client-side
searchText = request.POST["q"]
sqs = SearchQuerySet().filter(name=searchText)
data = []
for result in sqs:
data.append({"name": result.object.name})
return HttpResponse('{ success:true, searches:'+simplejson.dumps(data)+'}', mimetype = 'application/json')
Finally in your urls.py you should add:
(r'^searchlist/','someapp.views.searchlist'),
That was for it. Best wishes.
P.S.
I know this is not the greatest answer and there's lack of explanation, but as for me, I rather prefer a code example than verbal explanation.
SOLR has JSON output from its queries using wt=json param and can readily be consumed by ExtJS.
http://wiki.apache.org/solr/SolJSON?action=fullsearch&context=180&value=jsonp&titlesearch=Titles#JSON_Response_Writer
if you need to use jsonp you can specify a callback function via this param json.wrf=callback

Load data from bd in senchaTouch app using webservice who return a json

I try to display some data in my Sencha touch application, but it doesn't work... and i can't find what I'm doing wrong.
My webSiste return a json object who look like this
[{"name":"a","id":1}]
the script is getting the Json and display it:
Ext.regApplication({ name: 'Command',
phoneStartupScreen: 'phone-startup.png',
phoneIcon: 'apple-touch-icon.png',
launch: function(){
this.viewport = new Ext.Panel(
{
layout: 'fit',
fullscreen: true,
items: [{xtype: 'list',
itemTpl: new Ext.XTemplate('<div>{name}</div>'),
store: stores
}],
dockedItems: [{xtype: "toolbar",
dock: "top",
title: 'MovieCommand',
items: [{ui: 'back',text: 'back',handler: function(){}}]
}]
});
}
});
Ext.regModel('Commands', {
fields: ['name', 'id' ]
});
var stores = new Ext.data.Store(
{model: 'Commands',
proxy: {type: 'scripttag',
url: 'http://localhost:8080/GTI710/commandes/liste.htm',
format: 'sencha',
reader: new Ext.data.JsonReader ({
type: 'json',
})
},
});
stores.load();
I don't have any error in the java script but nothing is displayed.
I just want to have the "a" displayed but it doesn't work, I don't know why...
The ScriptTagProxy, which you are using, requires a response from server that's composed of legitimate Javascript code.
Specifically, the code is a callback function with the desired JSON data you what as the its first argument:
someCallback([{"name":"a","id":1}]);
The name of someCallback is generated dynamically by Sencha Touch when the request is sent. In other words, your attempt to store the response with a static file will not work.
The name of someCallback is passed as a parameter in the GET request sent by Sencha Touch, the key of which defaults to callback.
If you don't want to have a web server as the data source, checkout Ext.util.JSONP.