ExtJS Replace Gridpanel Store - json

Is there anyway to remotely override/replace a GridPanel's store?
I have a grid that has a dummy store as I get an error if I don't declare as store:
this.ds is undefined
When my form is submitted, it makes a GET REST call & loads a JSON store with the results. I want this store to be the store of my grid and show it underneath the formPanel.
I can get it to show & return JSON but can't seem to replace the store.
I tried using
searchGrid.store = formStore //the JSONStore returned from form submit
EDIT
This if the data store:
var formStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '...',
method: 'GET'
}),
root: 'Report',
fields:[
....]
});
This is the loading / changing of the store:
var data = this.getForm().getValues();
formStore.load({
params: {
fields: Ext.encode(data)
}
});
var grid = Ext.getCmp('search');
Ext.apply(grid, {store: formStore});
grid.show();

Try this
myGridPanel.getStore().proxy.setApi({read: url});
myGridPanel.getStore().load();
I'm using this solution when I want to read data from another url

grid.reconfigure(store, colModel);
Works fine for me. Is the formStore.data compatible with Grid's columns configuration? You don't need to specify the column model in the reconfigure call if it didn't change.
Show a slice of your formStore.data and grid configuration.

Have you tried Ext.apply()?
From the api:
apply( Object object, Object config, Object defaults ) : Object
EDIT:
Here's how you use it:
Ext.apply(myGrid, { store : mystore }); //no need for the third parameter, but if you do want a default, then you can use one

Should the root is inside reader? Like this
var formStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '...',
method: 'GET'
}),
reader: {
type: 'json',
root: 'Report'
},
fields:[
....]
});

I managed to solve this by moving the jsonStore to the grid itself and make it a singleton. Then reference to it from the form using StoreMgr

Related

Sencha/Extjs rest call with all parameters

I'm using ExtJs 5.1.1 and I've written a simple view with a grid, and selecting one row the corresponding model property are editable in some text fields.
When editing is completed the button 'save' call Model.save() method, which use the rest proxy configured to write the changes on the server.
The call made by the proxy are two, first is OPTIONS call to know which method are allowed, second call is a PUT.
My problem is PUT json contains only the changed attributes.
I would like that my application sends all the attributes in PUT, instead only the changed subset.
Is this a proxy configuration, or should I use another kind of proxy, like ajax?
Some code snippet:
Model:
Ext.define('myApp.model.CvModel', {
extend: 'Ext.data.Model',
alias: 'viewmodel.cv',
idProperty : 'code',
proxy: {
type: 'rest',
url: 'http://localhost:8080/CV/resource/rest/cvs/CodeSystem/Domain',
paramsAsJson: true,
reader: {
type: 'json',
rootProperty: 'Test_data'
}
},
fields: [{
...
Controller:
onSave: function () {
var selCv = this.getViewModel().get('selectedCv');
selCv.save();
....
You need to specify a writer config on your proxy with writeAllFields: true. By default it's false, and the default writer itself is just {type: 'json'}.

Backbone model .toJSON() doesn't work after .fetch()

Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});

Extjs is passing my cfc a json string that I can not read

I am playing with the ExtJs4 cartracker application written by existdisolve. I was able to change his queries from rest requests to ajax requests. I also modified the api calls to use ajax to make ajax requests for updates.
I am not getting form or url data passed to my cfc. Instead, in firebug I see JSON passed. I am confused if it is not passed in the form or the url, how is this passed and how do I get to the data? I have tried deserialized the form and url and dumping these after the deserialize and I am told that it is not json.
Where would I find the json?
I am not allowed to post a picture. But it looks like this in the xhr window:
JSON
Active true
ColorID null
Shortname red
Longname Blood Red
So if it is being passed why can I not get to it?
Edit:
#existdissolve - I replaced the rest.js with ajax.js which looks like this:
/**
* Abstract REST proxy
*/
Ext.define('CarTracker6.proxy.Ajax', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.baseajax',
/*format: 'json',*/
limitParam: 'max',
startParam: 'offset',
sortParam: 'sortorder',
writer : {
type : 'ajax',
encode : false,
writeAllFields : true,
root : 'data',
allowSingle : true,
batch : false,
method: 'post',
params: { record: 'record' },
writeRecords : function(request, data) {
request.jsonData = data;
return request;
}
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'count'
},
api: {
read: 'api/option/colors.cfc?method=getcolors',
create: 'api/option/colors.cfc?method=addcolors',
update: 'api/option/colors.cfc?method=updatecolors',
destroy: 'api/option/colors.cfc?method=deletecolors'
}
});
My read works perfectly and I can call the correct cfcs for colors, statuses, etc. and retrieve the requisite data. I am looking to pass parameters to the CFCs and that is not working.
see http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.writer.Json-cfg-encode:
if the encode property of your writer is set to false, all data is sent as raw post body. Instead, you can use
encode: true,
root: 'data', // must be set if encode is true

knockout's viewModel does not get updated

I have the following knockout's viewModel :
var viewModel={
businessName: "",
....
}
I also tried to identify the field like this: businessName: ko.observable("")
Then, I have a load method that requests for a JSon with a newly populated data
And this is how I'm trying to apply the new data:
$.ajax({
//
url: "#Html.Raw(#Url.Action("Load"))",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
//OPTION 1:
viewModel.businessName = result.vm.BusinessName;
//OPTION 2:
var viewModel2 = ko.mapping.fromJS(result.vm);
console.log(viewModel2.businessName);
}
});//ajax
As a result:
if I use Option1, I get the new data but it does not get updated on the page.
If I use Option2, it writes "undefined"
Please advise how can I update the new data on the page?
I checked the similar topics but there is no answer that helps
PS
It seems I resolved OPTION 1. But still don't understand why OPTION 2 does not work
ko.observable is a function, not a property. So you get it's value like this:
var whatsTheValue = myVM.MyObservable();
and you set it like this:
myVM.MyObservable(newValue);
This is all in the docs.
Note, however, when using the data-bind syntax in your HTML, you don't need to explicitly unwrap your observable by using the parenthesis because KO is smart enough to do it automatically:
<span data-bind="text: MyObservable"></span>
You have to use ko.observable in the ViewModel and access/write it accordingly.
var myViewModel = {
businessName = ko.observable('')
};
...
$.ajax({
...
success: function(result) {
myViewModel.businessName(result.vm.BusinessName);
},
...
});
Otherwise your view won't have any clue you changed businessName. In the implementation ko.observable, besides actually storing the new value, broadcasts some events to your view, letting it know the stored value changed.

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.