sending json data to a grid - javascript

I want to send the firstname mike using json to an extjs grid, that reads json.However my knowledge in Json is limited,i don't know how to create the string firstname in json and i'm failing to achieve it.Any help please on how to do so?
//java code
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class JsonForm extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
}
//grid
Ext.onReady(function(){
Ext.define('Employee',{
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
reader: 'json'
},
fields: [{
name: 'FirstName',
type: 'string'
}]
});
var gridStore = Ext.create('Ext.data.XmlStore', {
model: 'Employee',
autoLoad: true,
proxy: {
type: 'ajax',
url: '',
reader: {
type: 'json',
root: ''
}
}
});
grid = Ext.create('Ext.grid.Panel', {
store: gridStore,
columnLines: true,
frame: true,
columns: [
{text: "First Name", flex:1, dataIndex: 'FirstName', tdCls: 'no-dirty'},
],
renderTo:Ext.getBody(),
width: '100%',
height: 650
});
});

I believe dataIndex value you have is not correct, you should use field's property name as the value for dataIndex.
dataIndex:'name' instead of what you have..
Take a look at this page from their docs, it might help more
http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.grid.Panel

Related

Extjs 4.2 autosync dynamic grid store

I have a grid with dynamic columns:
MODEL
Ext.define('App.mdlCriteriosConcurso', {
extend: 'Ext.data.Model',
fields: [
]
});
STORE
Ext.define('App.strCriteriosConcurso', {
extend: 'Ext.data.Store',
model: 'App.mdlCriteriosConcurso',
autoLoad: false,
proxy: {
type: 'ajax',
api: {
read: 'some url',
update: 'some url',
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'total'
},
writer: {
root: 'records',
encode: true,
writeAllFields: true
}
}
});
GRID
var almacenCriteriosConcurso = Ext.create('App.strCriteriosConcurso');
//Some code ...
{
xtype:'grid',
itemId:'gridCriteriosConcursoV4',
store:almacenCriteriosConcurso,
plugins: [Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 2})],
columns:[]
}
//Some code...
CONTROLLER
Here in the controller I have the next piece of code:
Ext.ComponentQuery.query('viewFichaDetalle #tabpanelsecundario4_1 #gridCriteriosConcursoV4')[0].getStore().addListener('metachange',function(store,meta){
var columnas=0;
var renderer1 = function(v,params,data){
if(v==''){
return '<div style="background-color:#F5FAC3;color:blue;">'+Ext.util.Format.number(0,'0.000,00/i')+'</div>';
}
else{
return '<div style="background-color:#F5FAC3;color:blue;">'+Ext.util.Format.number(v,'0.000,00/i')+'</div>';
}
};
var renderer2 = function(v,params,data){
if(v=='' || v==0){
return '<div style="background-color:#F5FAC3;color:green;">'+Ext.util.Format.number(0,'0.000,00/i')+'</div>';
//return '';
}
else{
return '<div style="background-color:#F5FAC3;color:green;">'+Ext.util.Format.number(v,'0.000,00/i')+'</div>';
}
};
Ext.each(meta.columns,function(col){
if(columnas==2){
meta.columns[columnas].renderer = renderer1;
}
if(columnas>=3){
meta.columns[columnas].renderer = renderer2;
}
columnas++;
},this);
Ext.suspendLayouts();
Ext.ComponentQuery.query('viewFichaDetalle #tabpanelsecundario4_1 #gridCriteriosConcursoV4')[0].reconfigure(store, meta.columns);
Ext.ComponentQuery.query('viewFichaDetalle #tabpanelsecundario4_1 #gridCriteriosConcursoV4')[0].setTitle("<span style='color:red;font-weight:bold;font-size: 12pt'>Criterios del Concurso con ID:</span> "+"<span style='color:black;font-weight:bold;font-size: 12pt'>"+this.IdConcurso+"</span>");
Ext.resumeLayouts(true);
},this);
I create the columns in the php, using the metadata.
With this code I add some renderers to the grid columns. And I see all the data perfect, and can edit the data.
In the php y generate the column and the field like this:
$array_metadata['columns'][]=array("header"=>"<span style='color:blue;'>Resultado</span>","dataIndex"=>"puntos_resultado","width"=>82,"align"=>"right","editor"=>"textfield");
$array_metadata['fields'][]=array("name"=>"puntos_resultado","type"=>"float");
And then pass $array_metadata to 'metaData' response.
But when I try to sync or autosync the store I get this error:
Uncaught TypeError: Cannot read property 'name' of undefined
at constructor.getRecordData (ext-all-dev.js:62247)
at constructor.write (ext-all-dev.js:62192)
at constructor.doRequest (ext-all-dev.js:102306)
at constructor.update (ext-all-dev.js:101753)
at constructor.runOperation (ext-all-dev.js:106842)
at constructor.start (ext-all-dev.js:106769)
at constructor.batch (ext-all-dev.js:62869)
at constructor.sync (ext-all-dev.js:64066)
at constructor.afterEdit (ext-all-dev.js:64162)
at constructor.callStore (ext-all-dev.js:101428)
UPDATE 1
I have fount this thread in Sencha Forums link , and I have tried all posibles solutions and Im getting allways the same error.
The error tells us that you don't fill the model's fields array properly, because that is where name is a required config. In ExtJS 4, you have to add all fields to the model for the sync to work properly.
To be exact, the Model prototype has to be filled with the correct fields before the instances are created.
This means that you will have to override the reader's getResponseData method, because between Ext.decode and readRecords you will have to prepare the model prototype by setting the fields as returned from the server; something like this:
App.mdlCriteriosConcurso.prototype.fields = data.fields;

Unable to populate Highchart at runtime using json data

I am trying to populate highchart by sending data through servlet . My servlet is like:
package com.sandeep.visual.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.sandeep.visual.data.Student;
#WebServlet("/StudentJsonDataServlet")
public class StudentJsonDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentJsonDataServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Student> listOfStudent = getStudentData();
Gson gson = new Gson();
String jsonString = gson.toJson(listOfStudent);
response.setContentType("application/json");
response.getWriter().write(jsonString);
}
private List<Student> getStudentData() {
List<Student> listOfStudent = new ArrayList<Student>();
Student s1 = new Student();
s1.setName("Sandeep");
s1.setComputerMark(75);
s1.setMathematicsMark(26);
listOfStudent.add(s1);
Student s2 = new Student();
s2.setName("Bapi");
s2.setComputerMark(60);
s2.setMathematicsMark(63);
listOfStudent.add(s2);
Student s3 = new Student();
s3.setName("Raja");
s3.setComputerMark(40);
s3.setMathematicsMark(45);
listOfStudent.add(s3);
Student s4 = new Student();
s4.setName("Sonu");
s4.setMathematicsMark(29);
s4.setComputerMark(78);
listOfStudent.add(s4);
return listOfStudent;
}
}
And I am able to get the desired json in my html page as:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Dynamic HighChart</title>
<script type="text/javascript" src="./js/jquery.min_1.8.2.js"></script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'StudentJsonDataServlet',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
// Populate series
var nameArr = new Array();
var processed_json = new Array();
for (i = 0; i < data.length; i++) {
nameArr.push([data[i].name]);
processed_json.push([parseInt(data[i].mathematicsMark),parseInt(data[i].computerMark)]);
}
console.log("name array : " + nameArr);
console.log("FinalArray : " + processed_json);
// draw chart
$('#container').highcharts({
chart: {
type: "line"
},
title: {
text: "Marks obtained"
},
xAxis: {
categories: [nameArr]
},
yAxis: {
title: {
text: "Marks obtained"
}
},
series: [{
name: nameArr,
data: processed_json
}]
});
}
});
});
</script>
</body>
</html>
Now the best thing is that I am able to populate the HighChart but it doesn't appear as I want it to.
I have tried the same above example using google chart and I am getting something like this:
Which is my intended result what I want to get.
But with highchart I am getting something like this:
How can I achieve the same result shown in picture 1 through highChart.
Looking forward to your solutions. Thanks in advance.
To achieve that result, you need to create two series in the beginning:
var series = [{
name: "Mathematics mark",
data: []
}, {
name: "Computer mark",
data: []
}];
Now, add points (marks) to these series:
$.each(data, function(i, point) {
series[0].data.push([
point.name,
parseInt(point.mathematicsMark)
]);
series[1].data.push([
point.name,
parseInt(point.computerMark)
]);
});
Now, set xAxis.type as category, so points' names will be used as xAxis labels:
$('#container').highcharts({
xAxis: {
type: 'category'
},
series: series
});
Working demo: https://jsfiddle.net/sg9rghyg/
Here is working fiddle
Update as per JSON shared , below is complete code:
var seriesData=[];
var data =[{"name":"Sandeep","mathematicsMark":26,"computerMark":75}, {"name":"Bapi","mathematicsMark":63,"computerMark":60},{"name":"Raja","mathematicsMark":45,"computerMark":40},{"name":"Sonu","mathematicsMark":29,"computerMark":78}] ;
$.each (data, function(i){
seriesData.push({name:data[i].name,data: [parseInt(data[i].mathematicsMark),parseInt(data[i].computerMark)]});
}) ;
Use this seriesData in chart
Instead of separate arrays of names and data
[{
name: nameArr,
data: processed_json
}]
Do As below:
[{
name: data[i].name,
data: [parseInt(data[i].mathematicsMark),parseInt(data[i].computerMark)] // or your processed_json
}]

Extending Ext.data.Store

Here is the super class:
Ext.define('My.store.Direct', {
extend: 'Ext.store.Direct',
paramsAsHash: true,
proxy: {
reader: {
type: 'json',
root: 'data',
totalProperty: 'total'
},
type: 'direct',
}
});
In subclasses I only need to set the API config. I tried:
Ext.define('My.store.User', {
extend: 'My.store.Direct',
model: 'My.model.User',
storeId: 'user',
constructor: function () {
this.callParent(arguments);
this.getProxy().api.read = RPC.UserApi.read;
}}
);
Ext.define('My.store.Post', {
extend: 'My.store.Direct',
model: 'Mehr.model.Post',
storeId: 'post',
constructor: function () {
this.callParent(arguments);
this.getProxy().api.read = RPC.PostApi.read;
}}
);
Unfortunately, after executing the code both store will have the api.read of the first subclass. What is wrong with it? What is proper method of extending stroes?
Create your proxy in constructor, otherwise proxy goes to the prototype of My.store.Direct and because it is an object, not a primitive type (int, string, bool), it is accessed by reference. Thus, changing proxy in one instance changes all instances - there is only one proxy in fact.
So base class should be defined similar to this
Ext.define('My.store.Direct', {
extend: 'Ext.data.DirectStore',
paramsAsHash: true,
constructor:function(config) {
Ext.merge(config, {proxy: {
reader: {
type: 'json',
root: 'data',
totalProperty: 'total'
},
type: 'direct'
}
});
this.callParent([config]);
}
});

Extjs load xmlfile attributes into store

i am trying to load attribute values into an extjs store with the following code:
Ext.define('assert', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', mapping: '#id' },
{ name: 'test', mapping: '#test' },
{ name: 'name', mapping: '#name' }
]
});
var store = new Ext.data.Store({
model: 'assert',
proxy: {
type: 'ajax',
url : 'App/data/rules.xml',
reader: {
type: 'xml',
model:'assert',
record: 'assert'
}
}
});
but the store always shows up empty.
Heres a blanked out excerpt from the xml file:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="****" xmlns:axsl="****" xmlns:sch="*****" xmlns:iso="******" xmlns:xs="*****" xmlns:rule="******">
<title>test Schematron</title>
<pattern name="test Schematron">
<rule context="*****" name="*****">
<assert test="*****" diagnostics="*****" name="*****" id="****" comment="" uval="" source="****"/>
<assert test="******" diagnostics="****" name="****" id="***" comment="" uval="" source="*****"/>
</rule>
</pattern>
</schema>
Im very new to reading XML files to ExtJS, so it would be great if one of you could
show me the proper way to map those attributes.
There's nothing wrong with your XML file. Your problem is that ExtJS stores don't Load data on automatically on creation by default. You have to either enable the autoLoad or load the Store manually with the load function:
Ext.define('assert', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', mapping: '#id' },
{ name: 'test', mapping: '#test' },
{ name: 'name', mapping: '#name' }
]
});
var store = new Ext.data.Store({
model: 'assert',
autoLoad: true, // The store will start loading as soon as the framework is ready.
listeners: {
load: function(){ // This gets executed when your store is done loading.
console.log('Loaded!!');
}
},
proxy: {
type: 'ajax',
url : 'data/rules.xml',
reader: {
type: 'xml',
model:'assert',
record: 'assert'
}
}
});
Ext.onReady(function(){
console.log('Ready!!');
store.load({ // This works too!
scope: this,
callback: function(records, operation, success) {
console.log('loaded records!!');
}
});
});
Remember that the load is asynchronous and you have to wait until the load is done to be able to use the data!
I recommend that you check the API doc too see all that you can do with the load function.
extjsjavascript

Unable to read Model Records from store by using store.getById()

I am trying to acheive i18n for my sencha Ext JS App.
I used the impl from [https://github.com/elmasse/Ext.i18n.Bundle-touch/blob/master/i18n/Bundle.js][1], but with more simplified version.
Basically, I have a store [webUi.util.rb.ResourceBundle] linked to model [webUi.util.rb.model.KeyValPair], trying to load the json data to the store. Once the data is loaded i am trying to access the loaded data through different store functions . But not getting it..? Can anyone find what I am missing..?
Store class
Ext.define('webUi.util.rb.ResourceBundle', {
extend: 'Ext.data.Store',
requires: [
'webUi.util.rb.model.KeyValPair'
],
constructor: function(config){
config = config || {};
var me = this;
Ext.applyIf(config, {
autoLoad: true,
model: 'webUi.util.rb.model.KeyValPair',
proxy:{
type: 'ajax',
url: webUi.util.AppSingleton.uiRsrcUrl,
noCache: true,
reader: {
type: 'json',
rootProperty: 'bundle'
},
getParams: Ext.emptyFn
},
listeners:{
'load': this.onBundleLoad,
scope: this
}
});
me.callParent([config]);
me.getProxy().on('exception', this.onBundleLoadException, this, {single: true});
},
onBundleLoad: function(store, record, success, op) {
if(success){
this.fireEvent('loaded');
} else{
this.fireEvent('loadError');
}
},
onBundleLoadException: function(){
console.dir(arguments);
},
onReady: function(fn){
this.readyFn = fn;
this.on('loaded', this.readyFn, this);
},
getMsg: function(key){
return this.getById(key)? Ext.util.Format.htmlDecode(this.getById(key).get('val')) : key + '.undefined';
}
});
Model Class
Ext.define('webUi.util.rb.model.KeyValPair', {
extend: 'Ext.data.Model',
config: {
idProperty: 'key',
fields: ['key', 'val']
}
});
JSON Response
{"bundle":[{"key":"one","val":"Oneee"},{"key":"two","val":"Twooo"}]}
my Code
var bundle = Ext.create('webUi.util.rb.ResourceBundle');
bundle.onReady(function(){
console.log('%%%%%%%%%%%%%');
console.log(bundle.getMsg('one'));
console.log(bundle.getById('one'));
console.log(bundle.getAt(0));
});
console.log
%%%%%%%%%%%%%
one.undefined
null
constructor {raw: Object, modified: Object, data: Object, hasListeners: HasListeners, events: Object…}
try using bundle.data.getMsg()

Categories

Resources