Can't access specific data in jsonfile - Flutter - json

I have this json file :
{
projects: [
{
projectId: 3
projectName: "Complexe hotelier croisette",
workflow: "en cours",
realCalendars: [
{
id: 29,
start: 1630590443000
end: 1648475243000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
scheduledCalendars: [
{
id: 30,
start: 1630590443000
end: 1646059643000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
lastPlanningModif: 1639320443000
planned: 164,
actual: 142,
remaining: 25,
resourceTaskNumber: 1,
projectTaskNumber: 18,
leaderId: 8,
resourceIds: [8, 7, 6],
dashbordField: 3,
dashbordTendency: 1,
weatherComments: [
{
message: "weather 5",
date: 1645195643000
source: 1
taskId:0
projectId: 3
authorId: 8,
messageId: 31,
messageParentId: 32
},
{
message: "weather 6",
date: 1643813243000
source: 1
taskId: 0
projectId: 3
authorId: 8,
messageId: 33,
messageParentId: 34
},
{
message: "weather 7",
date: 1642776443000
source: 1
taskId: 0
projectId: 3
authorId: 7,
messageId: 35,
messageParentId: 36
},
],
projectComments: [
{
message: "Time 3",
date: 1642776443000
source: 4
taskId: 3789
projectId: 3
authorId: 7,
messageId: 37,
messageParentId: 38
},
{
message: "Time 4",
date: 1639838843000
source: 4
taskId: 3876
projectId: 3
authorId: 8,
messageId: 39,
messageParentId: 40
},
{
message: "Time 5",
date: 1638888443000
source: 2
taskId: 3258
projectId: 3
authorId: 8,
messageId: 41,
messageParentId: 42
},
],
},
{
projectId: 2
projectName: "Festival de la moutarde de Dijon",
workflow: "objectif",
realCalendars: [
{
id: 23,
start: 1682689643000
end: 1696686443000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
scheduledCalendars: [
{
id: 24,
start: 1682689643000
end: 1696686443000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
lastPlanningModif: 1646059643000
planned: 150,
actual: 0,
remaining: 150,
resourceTaskNumber: 2,
projectTaskNumber: 10,
leaderId: 4,
resourceIds: [4, 6, 7, 8],
dashbordField: 4,
dashbordTendency: 2,
weatherComments: [
{
message: "weather 4",
date: 1674744443000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 25,
messageParentId: 26
}
],
projectComments: [
],
},
{
projectId: 1
projectName: "Red Is Dead",
workflow: "en cours",
realCalendars: [
{
id: 9,
start: 1642430843000
end: 1669387643000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
scheduledCalendars: [
{
id: 10,
start: 1642430843000
end: 1666705643000
type: 0
remark: NULL
status: 0
calendarId: NULL
}
],
lastPlanningModif: 1645109243000
planned: 280,
actual: 58,
remaining: 222,
resourceTaskNumber: 5,
projectTaskNumber: 36,
leaderId: 4,
resourceIds: [4,5,6],
dashbordField: 2,
dashbordTendency: 3,
weatherComments: [
{
message: "weather 1",
date: 1645800443000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 11,
messageParentId: 12
},
{
message: "weather 2",
date: 1643986043000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 13,
messageParentId: 14
},
{
message: "weather 3",
date: 1643122043000
source: 1
taskId: 0
projectId: 1
authorId: 4,
messageId: 15,
messageParentId: 16
},
],
projectComments: [
{
message: "Time 1",
date: 1642862843000
source: 4
taskId: 1234
projectId: 1
authorId: 5,
messageId: 17,
messageParentId: 18
},
{
message: "Time 2",
date: 1642258043000
source: 4
taskId: 1235
projectId: 1
authorId: 5,
messageId: 19,
messageParentId: 20
},
{
message: "Task 1",
date: 1641826043000
source: 2
taskId: 1234
projectId: 1
authorId: 5,
messageId: 21,
messageParentId: 22
},
],
}
],
avatars: [
{
resourceId: 8,
idSource: 81,
resourceName: "Alain Martoni",
trigram: "AMO",
imgBase64: ""
},
{
resourceId: 4,
idSource: 41,
resourceName: "Odile Deray",
trigram: "ODE",
imgBase64: ""
},
{
resourceId: 7,
idSource: 71,
resourceName: "Patrick Bialès",
trigram: "PBI",
imgBase64: " "
},
{
resourceId: 5,
idSource: 51,
resourceName: "Serge Karamazov",
trigram: "SKA",
imgBase64: ""
},
{
resourceId: 6,
idSource: 61,
resourceName: "Simon Jérémi",
trigram: "SJE",
imgBase64: ""
}
]
}
Here I try to display specific data from the json (here I want to display what's in "projects")
var resp = response.body;
print("mydata : " + resp['projects'].toString());
Then I tried adding a jsonDecode :
var resp = jsonDecode(response.body);
print("mydata : " + resp['projects'].toString());
Then jsonEncode :
var resp = jsonEncode(response.body);
print("mydata : " + resp['projects'].toString());
Then both :
var resp = jsonDecode(jsonEncode(response.body));
print("mydata : " + resp['projects'].toString());
When I try display only "resp" it works, but it's the access to a specific part (like "projects") of the JSON that doesn't work. The only thing that work is with an int and it display the specific caractere of the index as if the JSON was read as a String.
var resp = jsonDecode(jsonEncode(response.body));
print("mydata : " + resp[0].toString());
//display the first caracter of the JSON
The thing is when I read the response of POST HTTP requests, using jsonEncode then jsonDecode works perfectly, I can then easily access any part of the JSON :
var response = await http.post(
Uri.parse(url),
body: jsonEncode({
"jsonrpc": "2.0",
"id": "10",
"method": "method",
"params": [someParams]
})
);
var resp = jsonDecode(response.body);
print("response body : " + resp['projects'].toString());
//display the "project" part of the JSON response
But all this doesn't work when trying to access specific parts of my first JSON file.
Is there something wrong with my JSON file ?
Thanks for helping.
Update : commas are missing in the json, I corrected it but still the same probleme

I ran your JSON through a JSON formatter / validator and yes, your json was missing some commas and whatnot.
Check out this Gist I created for your decoding - run it through DartPad.Dev and check out.
I made sure the JSON was a proper string before I ran it through the jsonDecode, then I just simply access its values like this:
var decodedJSON = jsonDecode(json);
print(decodedJSON['projects'].length);
print(decodedJSON['projects'][0]['projectName']);
print(decodedJSON['avatars'].length);
print(decodedJSON['avatars'][0]['resourceName']);
I got the values I expected:
3
Complexe hotelier croisette
5
Alain Martoni
I think your issue was just badly formatted JSON coming out of the pipe. Check out the Gist and let me know.

Related

jsondecode loading issue in dart

I try to run below code in flutter App but it loads half JSON data, same API when running for a web app it works fine.
Any idea how to solve this issue?
Example
Future <List> test() async{
final response = await http.post(
"https://xyz/allData",
body: jsonEncode({
"email": "email"
}),
headers: {
HttpHeaders.contentTypeHeader: ContentType.json.toString(),
HttpHeaders.authorizationHeader: token
});
final data= json.decode(response.body);
OR
Map<String, dynamic> data =json.decode(response.body);
Error
half JSON fetch by above code
below content I recieved :
{success: true, msg: Loaded, content:
{total: 3, on: 0, off: 3,
on: {},
off: {
11: {id: 11, last_data: N/A,value: {N/A: {name: N/A, value: N/A}},
name: 01, type: temp, upper: 20, lower: 10, email: [], phn_list: [], id: 01,status: 0, freq: 10, description: 01, status_notf: 0, lat_map: 0, lng_map: 0, html: html},
12: {id: 12, last_data: N/A, value: {N/A: {name: N/A, value: N/A}},
name: 02, type: temp, upper: 20, lower: 10, email: [], phn_list: [], id: 02, status: 0,freq: 10, description: 02, status_notf: 0, lat_map: 0, lng_map

{this.state.object} Objects are not valid as a React child

I have a response json like this:
{
"variables": {
"lock": 0,
"pos": 55,
"pos_on": 55,
"pos_off": 150
},
"id": "11",
"name": "Lock_table_2",
"hardware": "esp8266",
"connected": true
}
and I try to show the lock value in 'variables' object
so I write
constructor(props) {
super(props)
this.state = {
dock_1: {}, // define a empty json
dock_2: {},
dock_3: {},
}
}
pingIP() {
axios
.get('http://192.168.50.225:8888/test_check')
.then(response => {
let data = response.data.list; // return value is a list
this.setState({ // every 2 sec setState
dock_1: data[0], // data[0] -> 192.168.50.40's json
dock_2: data[1],
dock_3: data[2],
})
})
}
render(){
return (
<p>{this.state.dock_1.variables.lock}</p>
);
}
but I got this error
in here
So I tried this
render(){
return (
<p>{this.state.dock_1.variables}</p>
);
}
then here comes the another error message
in here
here is the get request return value
{
"list": [
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_1",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_2",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_3",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
}
]
}
the return value is a list
in order to get first value so I wrote data[0], data1 ...
what's happening in here?
I think your response is an array of 3 items like this:
[
{
variables: {
lock: 0,
pos: 55,
pos_on: 55,
pos_off: 150
},
id: "11",
name: "Lock_table_2",
hardware: "esp8266",
connected: true
},
{
variables: {
lock: 1,
pos: 44,
pos_on: 56,
pos_off: 151
},
id: "11",
name: "Lock_table_3",
hardware: "esp8267",
connected: false
},
{
variables: {
lock: 2,
pos: 45,
pos_on: 57,
pos_off: 152
},
id: "11",
name: "Lock_table_4",
hardware: "esp8268",
connected: true
}
]
So you can access the dock 1 variable lock using Inline If with Logical && Operator to prevent null exception.
<p>{this.state.dock_1.variables && this.state.dock_1.variables.lock}</p>
A sample working codesandbox with a fake api:
https://codesandbox.io/s/stoic-chaplygin-r1yxd

How can i get the entity value after checking the type?

(4) [{…}, {…}, {…}, {…}]
0: {entity: "lovely meeting", type: "Calendar.Subject", startIndex: 53, endIndex: 66, score: 0.9183444}
1: {entity: "california", type: "Calendar.Location", startIndex: 27, endIndex: 36, score: 0.922538459}
2: {entity: "today", type: "builtin.datetimeV2.date", startIndex: 18, endIndex: 22, resolution: {…}}
3: {entity: "4am", type: "builtin.datetimeV2.time", startIndex: 41, endIndex: 43, resolution: {…}}length: 4__proto__: Array(0)
These 4 elements are part of Entities, what i want is to check if type is equal to let's say Calender.Location and worth noting that we don't always have the 4 elements we could have one or none, and even when we do have 4 the entity type Calender.Location doesn't have to be index number 1, what i have tried included testvar.entities.length and testvar.entities[0].type not knowing the ID of each makes it impossible .
Example of what i want:
i want to parse the Json input for a type Calendar.location in entities, it might exist and might not and its exact id is not known(ranges between 0 and 4), if i do find it i should return the entity associated with it in this case california.
const test =[
{entity: "lovely meeting", type: "Calendar.Subject", startIndex: 53, endIndex: 66, score: 0.9183444},
{entity: "california", type: "Calendar.Location", startIndex: 27, endIndex: 36, score: 0.922538459},
{entity: "today", type: "builtin.datetimeV2.date", startIndex: 18, endIndex: 22, resolution: {}},
{entity: "4am", type: "builtin.datetimeV2.time", startIndex: 41, endIndex: 43, resolution: {}}
]
const getentitiesByType = (arr,type) => {
for(let i in arr ){
if(arr[i].type === type){
return arr[i].entity;
}
}
};
console.log(getentitiesByType(test,"Calendar.Location"))

Highcharts series data from JSON object

I am new to JSON and mvc so here is my issue. I am currently working on graphs using highcharts. I have a controller which returns a JSON object.
public JsonResult _GetChart_TrendPublicationTypeDetailed_Data(int
yearToDisplay)
{
//Types of publications to be considered
string[] publication_types = new string[] { "article", "book", "book_section", "conference_proceedings" };
//Get the list of outputs with usp authors
var uspPubs = _uspAuthoredPublications();
//List of years for which to display the data
List<int> yearRange = _getListOfYears(yearToDisplay, yearRangeFactor_10);
//Get the data
var data = from eprint_summary in localDB.Summary
where
eprint_summary.Year > (yearToDisplay - yearRangeFactor_10)
&& eprint_summary.Year <= yearToDisplay
&& publication_types.Contains(eprint_summary.TypeCode)
&& uspPubs.Contains(eprint_summary.EprintId)
//&& eprint_summary.refereed == "TRUE" //TODO: Confirm whether we need this filter in our counts
group eprint_summary by new { eprint_summary.Year, eprint_summary.TypeDesc } into typeTrend
orderby typeTrend.Key.Year, typeTrend.Key.TypeDesc
select new
{
Year = typeTrend.Key.Year,
Type = typeTrend.Key.TypeDesc,
Count = typeTrend.Count()
};
//Extract the series data
List<object> countData = new List<object>();
foreach (var item in data.ToList().Select(y => y.Type).Distinct().OrderBy(y => y))
{
List<int> yearlyData = new List<int>();
foreach (var year in yearRange)
{
var rec = data
.Where(y => y.Type == item)
.Where(y => y.Year == year)
.Select(y => y.Count).ToArray();
yearlyData.Add(
rec == null || rec.Length == 0 ? 0 : rec[0]
);
}
countData.Add(
new
{
name = item, //Name of the series
data = yearlyData.ToArray() //Array of data
}
);
}
//Form the json object using the series data and labels
return Json(
new
{
labels = yearRange.ToArray(),
series = countData
},
JsonRequestBehavior.AllowGet
);
}
The above is my JSON in controller.
I have my view as below where I am getting the JSON object but I do not know how to append to my graph as series. How would I convert the JSON object to something that the series accepts.
var seriesData = ' ';
var test = ' ';
function ajaxCall() {
$.ajax({
type: "post",
datatype: "Json",
async: true,
url: '#Url.Action("_GetChart_TrendPublicationTypeDetailed_Data", "ResearchCharts")',
data: { yearToDisplay: '#(DateTime.Now.AddYears(-1).Year.ToString())' },
success: function (data) {
seriesData = data;
test = seriesData.series;
//bindChart(test);
//alert(JSON.stringify(seriesData));
alert(JSON.stringify(test));
},
error: function () {
alert("An error occurred.");
}
});
}
//functions call
ajaxCall();
bindChart(test);
function bindChart(test) {
var test2 = [{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }];
$('#chartTrendsPublicationTypeDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016']
},
series: test2//[{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }]
});
Please help, just need to somehow pass the data to highcharts.
in the picture, I have added the series manually and it works, but I need to pass in a variable which the series property accepts.
Old Highcharts rendering code:
$('#chartTrendsPublicationRankDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: labels
},
series: seriesData
});
New Highcharts rendering code. This accepts my JSON objects successfully and renders the graphs.
function bindChartItemType(seriesData, labels) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartTrendsPublicationTypeDetailed',
type: 'line',
height: 500,
width: 500
},
credits: {
enabled: false
},
title: {
text: 'Trend of Publications by Item Type'
},
xAxis: {
categories: labels,
title: {
text: '<b>Year</b>'
}
},
yAxis: {
min:0,
title: {
text: '<b># of publications</b>'
}
},
series: seriesData
});
}
Feel free to add anything you like in the comments.
Regards
Shafraz Buksh

Load and save to grid in extjs from nested json

I have a nested json for employee leaves and inside which i have leave history and leave eligibility. i need to populate two grids with the json.i can't read from the json or write to it..Please Help...
My Json is...
{
"EmployeeLeaves": {
"ID": 37,
"LeaveEligibility": [
{
"Availed": 4,
"Fullpaydays": 6,
"Halfpaydays": 0,
"ID": 1,
"LeaveTypeId": 60,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 2,
"Fullpaydays": 6,
"Halfpaydays": 0,
"ID": 3,
"LeaveTypeId": 61,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 10,
"Fullpaydays": 10,
"Halfpaydays": 0,
"ID": 4,
"LeaveTypeId": 62,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 0,
"Fullpaydays": 8,
"Halfpaydays": 0,
"ID": 6,
"LeaveTypeId": 63,
"PersonId": 37,
"YearOfLeave": 2013
}
],
"LeaveHistory": [
{
"AppliedTo": "Vibha",
"ApprovalDate": "3/12/2013 12:00:00 AM",
"ApprovedBy": 12,
"Duration": 3,
"FromDate": "3/24/2013 12:00:00 AM",
"FullPayDays": 3,
"HalfPayDays": 0,
"ID": 1,
"LeaveTypeId": 60,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "onnulla",
"StatusId": 79,
"SubstitutePersonId": 13,
"ToDate": "3/26/2013 12:00:00 AM"
},
{
"AppliedTo": "Vibha",
"ApprovalDate": "3/12/2013 12:00:00 AM",
"ApprovedBy": 12,
"Duration": 1,
"FromDate": "3/30/2013 12:00:00 AM",
"FullPayDays": 1,
"HalfPayDays": 0,
"ID": 2,
"LeaveTypeId": 60,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "onnulla",
"StatusId": 79,
"SubstitutePersonId": 13,
"ToDate": "3/31/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "",
"ApprovedBy": 0,
"Duration": 2,
"FromDate": "2/13/2013 12:00:00 AM",
"FullPayDays": 2,
"HalfPayDays": 0,
"ID": 4,
"LeaveTypeId": 61,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "blha blah",
"StatusId": 70,
"SubstitutePersonId": 1,
"ToDate": "2/14/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "2/13/2013 4:35:16 PM",
"ApprovedBy": 2,
"Duration": 5,
"FromDate": "3/23/2013 12:00:00 AM",
"FullPayDays": 5,
"HalfPayDays": 0,
"ID": 5,
"LeaveTypeId": 62,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "oh..",
"StatusId": 71,
"SubstitutePersonId": 1,
"ToDate": "3/27/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "2/13/2013 4:35:16 PM",
"ApprovedBy": 2,
"Duration": 5,
"FromDate": "3/28/2013 12:00:00 AM",
"FullPayDays": 5,
"HalfPayDays": 0,
"ID": 6,
"LeaveTypeId": 62,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "oh..",
"StatusId": 71,
"SubstitutePersonId": 1,
"ToDate": "3/29/2013 12:00:00 AM"
}
],
"PLavailedcount": 2
}
}
My Models and store are as follows....
Ext.define('custom.writer.Json', {
extend: 'Ext.data.writer.Json',
getRecordData: function(record) {
Ext.apply(record.data, record.getAssociatedData());
return record.data;
}
});
Ext.define('AM.store.LeaveRequest', {
extend: 'Ext.data.Store',
model: 'AM.model.leaverequest',
autoLoad:true,
proxy: {
type: 'ajax',
url:'ARSENAWeb/employeeleave.json?id=37',
reader: {
type: 'json',
root: 'EmployeeLeaves'
},
writer:new custom.writer.Json({writeAllFields: true}),
api: {
read: 'ARSENAWeb/employeeleave.json?id=37',
update: 'ARSENAWeb/employeeleave.json?id=37',
create:'ARSENAWeb/employeeleave.json?id=37'
}}
});
Ext.define('AM.model.leaverequest', {
extend: 'Ext.data.Model',
fields: ['ID' ],
idProperty: 'ID',
autoSync:true,
uses: ['AM.model.MLeaveHistory','AM.model.MLeaveStatus'],
hasMany: {model: 'MLeaveHistory',model:'MleaveStatus'},
save: function() {
var me = this;
if (me.persistAssociations) {
me.set( me.getAssociatedData() );
}
me.callParent(arguments);
}
});
Ext.define('AM.model.MLeaveHistory', {
extend: 'Ext.data.Model',
fields: [
{name:'ApprovalDate'},
{name:'ApprovedBy'},
{name:'Duration'},
{name:'FromDate'},
{name:'FullPayDays'},
{name:'HalfPayDays'},
{name:'ID'},
{name:'LeaveTypeId'},
{name:'LossOfPayDays'},
{name:'PersonId'},
{name:'Remarks'},
{name:'StatusId'},
{name:'SubstitutePersonId'},
{name:'ToDate'}
],
belongsTo: 'AM.model.leaverequest'
});
Ext.define('AM.model.MLeaveStatus', {
extend: 'Ext.data.Model',
fields: [ {name:'Availed'},
{name:'Fullpaydays'},
{name:'Halfpaydays'},
{name:'ID'},
{name:'LeaveTypeId'},
{name:'PersonId'},
{name:'YearOfLeave'}
],
belongsTo: 'AM.model.leaverequest'
});
My Controller is
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores: ['LType','SleaveHistory','SLeaveStatus',
],
models: [
'LeaveType','MLeaveHistory','MLeaveStatus'
],
views: [
'Leave.LeaveRequest','Leave.LeaveHistoryGrid','Leave.LeaveStatusGrid','Leave.HolidayList'
],
init: function() {
this.control({
'viewport >
'LeaveLeaveRequest button[action=reset]': {
click: this.resetForm
},
'LeaveLeaveRequest button[action=save]': {
click: this.saveForm
},
'leaveleavehistorygrid actioncolumn': {
itemclick: this.cancelLeave
},
'leaveleavehistorygrid': {
itemdblclick: this.editLeave
}
});
},
resetForm: function(button){
button.up('form').getForm().reset();
},
saveForm: function(button){
var form = button.up('form').getForm();
form.getValues(true);
var fromDate =new Date( Ext.getCmp('startdate'));//.getValue();
var endDate = new Date(Ext.getCmp('enddate'));
// var nod=Ext.Date.parseDate(fromDate,'m')
// Date.parseDate( String input, String format ) : Date
// var nod=fromDate+endDate;
var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((fromDate.getTime() - endDate.getTime())/(oneDay)));
console.log(diffDays);
if (form.isValid()){
var record = form.getRecord();
var values = form.getValues();
// console.log(values);
if(!record){
var newRecord = new AM.model.leaverequest(values);
this.getLeaveRequestStore().add(newRecord);
}else {
record.set(values);
}}
} ,
cancelLeave: function (view, cell, rowIndex, colIndex, e, record, row) {
Ext.Msg.confirm('Remove Qualification', 'Are you sure?', function (button) {
if (button == 'yes') {
var store = Ext.getStore('LeaveRequest');
var newRecord = new AM.model.leaverequest(row);
console.log(record);
console.log(store);
store.remove(record);
store.sync();
}
}, this);
}
});
My Grids are:
Ext.define('AM.view.Leave.LeaveHistoryGrid' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.leaveleavehistorygrid',
title: 'Leave History',
store: 'LeaveRequest',
xtype: 'cell-editing',
plugins: [
Ext.create('Ext.grid.plugin.RowEditing', {
startEditByClick: function (){},
onEnterKey: function (){}
})
],
initComponent: function() {
this.cellEditing = new Ext.grid.plugin.CellEditing({
clicksToEdit: 1
});
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
this.columns= [
{header: 'Leave Type', dataIndex: 'LeaveTypeId',flex:1},
{header: 'Start Date', dataIndex: 'FromDate',renderer: Ext.util.Format.dateRenderer('m/d/y'),flex:1,editor: {
xtype: 'datefield',
forceSelection : true,
minValue: '01/01/06',
disabledDays: [0, 6],
allowBlank :false,
disabledDaysText: 'Plants are not available on the weekends'
}},
{header: 'End Date', dataIndex: 'ToDate',renderer: Ext.util.Format.dateRenderer('m/d/y'),flex:1, editor: {
xtype: 'datefield',
format: 'm/d/y',
minValue: '01/01/06',
disabledDays: [0, 6],
allowBlank :false,
disabledDaysText: 'Plants are not available on the weekends'
}},
{header: 'No of Days', dataIndex: 'Duration',flex:1},
// {header: 'Approval Status', dataIndex: 'leaveapprovalstatus',flex:1},
{header: 'Descriptions', dataIndex: 'Remarks',flex:1},
{header: 'Cancel Leave',flex:1,
xtype: 'actioncolumn',
width:30,
action:'cancel',
sortable: false,
items: [{
handler: function(view, cell, rowIndex, colIndex, e, record, row) {
this.addEvents('itemclick');
this.fireEvent('itemclick',view, cell, rowIndex, colIndex, e, record, row);
},
icon: 'ext-4.1.1a-gpl/ext-4.1.1a/docs/extjs/resources/themes/images/default/grid/page-first-disabled.gif',
tooltip: 'Cancel Leave'
}]
}]
this.callParent(arguments);
}
});
Ext.define('AM.view.Leave.LeaveStatusGrid' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.leaveleavestatusgrid',
title: 'Leave History',
store: 'LeaveRequest',
initComponent: function() {
this.columns= [
{header: 'Type Of Leave', dataIndex: 'typeofleave',flex:1},
{header: 'Available', dataIndex: 'startdate',flex:1},
{header: 'Availed', dataIndex: 'leaveavailed',flex:1},
{header: 'Balance', dataIndex: 'leavebalance',flex:1}];
this.callParent(arguments);
}
});
my form
Ext.define('AM.view.Leave.LeaveRequest', {
extend: 'Ext.form.Panel',
alias: 'widget.LeaveLeaveRequest',
// requires: [
// 'Ext.ux.form.MultiSelect',
// ],
title: 'Leave Request',
// frame:true,
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
items: [ {
text: 'Reset',
action: 'reset'
}, {
text: 'Save',
action: 'save'
}]
}],
initComponent: function() {
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
// var value,value1;
this.items = [{xtype:'fieldset',
layout:'hbox',
items:[{
xtype:'container',
layout:'anchor',
items:[{
xtype:'textfield',
fieldLabel : 'Type of Leave',
labelWidth:'130px',
allowBlank :false,
afterLabelTextTp1:required
},{
// xtype:'checkbox',
// boxLabel: 'Half Day ',
// name: 'durationofleave',
// inputValue: 'halfday',
// uncheckedValue: 'fullday',
// allowBlank :false,
// afterLabelTextTp1:required
// },{
xtype:'datefield',
//renderer: Ext.util.Format.dateRenderer('m/d/y'),
vtype:'daterange',
fieldLabel : 'From Date',
labelWidth:'130px',
id:'FromDate',
afterLabelTextTpl: required,
name : 'FromDate',
endDateField: 'ToDate',
//minValue: new Date(),
allowBlank :false,
afterLabelTextTp1:required
},{
xtype:'datefield',
vtype:'daterange',
renderer: Ext.util.Format.dateRenderer('m/d/y'),
fieldLabel : 'To Date',
id:'ToDate',
startDateField: 'FromDate',
labelWidth:'130px',
// onExpand: function() {
// var field = Ext.getCmp('startdate');
// value: field.getValue();
// value1 = this.getValue();
// console.log(value+value1);},
// minValue: new Date(getCmp('startdate')),//Ext.Date.add(new Date(), Ext.Date.DAY, 7) ,
afterLabelTextTpl: required,
name : 'ToDate',
// change: function() {
// value = this.getValue('startdate')
// //var value = this.getValue('startdate');
// console.log(value);
// //this.picker.setValue(Ext.isDate(value) ? value : new Date());
//},
allowBlank :false,
afterLabelTextTp1:required
},{
xtype:'textfield',
fieldLabel : 'Number of days',
labelWidth:'130px',
id: 'textfield-field',
afterLabelTextTpl: required,
name : 'noofdays',
allowBlank :false,
afterLabelTextTp1:required
},
{
// xtype: 'multiselect',
// labelWidth:'130px',
// fieldLabel: 'Reporting Manager(s)',
// name: 'reportingmanager',
// id: 'multiselect-field',
// forceSelection : true,
// allowBlank: false,
// store: 'ReportingManager',
// mode: 'local',
// displayField: 'reportingmanager',
// valueField: 'value',
// ddReorder: true,
// afterLabelTextTp1:required
// },{
xtype:'textfield',
fieldLabel : 'Reason',
labelWidth:'130px',
afterLabelTextTpl: required,
name : 'reason',
allowBlank :false,
afterLabelTextTp1:required
}]
},{xtype:'container',width:'300px'},
{
xtype:'container',
items:[{xtype:'leaveleavestatusgrid',
store: 'LeaveRequest',
height: 200,
width: 500
}]
}]
},{xtype:'fieldset',
title:'Leave History',
items:[{xtype:'leaveleavehistorygrid',
store: 'LeaveRequest',
height: 300,
width: '100%'
}]
}];
this.callParent(arguments);
}
});
My json has a little change where the curly braces has been replaced by square braces
{
"EmployeeLeaves": [
{
"ID": 0,
"LeaveHistory": {
"Duration": 2,
"ApprovedBy": "shyam"
},
"PL": "'I don't care!' said the bear"
}
]
}
My model for the same has been changed to
Ext.define('AM.model.EMPLeaveRequest', {
extend: 'Ext.data.Model',
fields: [{
name: 'ID'
}, {
name: 'Duration',
mapping: 'LeaveHistory.Duration'
}, {
name: 'ApprovedBy',
mapping: 'LeaveHistory.ApprovedBy'
}],
proxy: {
type: 'ajax',
batchActions: false,
url: 'data/employeeleave.json',
autoAppendParams: false,
reader: {
type: 'json',
root: 'EmployeeLeaves',
useSimpleAccessors: false
}
}
});
My store is
Ext.define('AM.store.EMPLeaveRequest', {
extend: 'Ext.data.Store',
model: 'AM.model.EMPLeaveRequest',
autoLoad: true//,
});
There is no need for using associations....But only works for one set of data :(