ext.net How to load JSON into Grid panel - ext.net

I am using EXT.NET and have a question. I have a trouble to load json data into grid panel. My code is below. When tree item is clicked, selectNode function fires properly, but the JSON result can't be loaded into Grid panel.
How can I load into the Grid panel? Currently, white blank page pops up.
#model System.Collections.IEnumerable
#{
Layout = null;
var X = Html.X();
}
<script type="text/javascript">
var selectNode = function (item, record, node, index, event) {
Ext.Ajax.request({
url: "/Popup/GetDepartmentUser",
method: "POST",
params: {
id: record.data.id
},
callback: function (options, success, response) {
if (Ext.decode(response.responseText).success == false) {
Ext.Msg.alert("Failed", response.responseText);
} else {
var grid = App.theGrid;
grid.show();
grid.getStore().loadData(Ext.decode(response.responseText));
//Ext.Msg.alert("Success", response.responseText);
}
},
failure: function (response, options) {
Ext.MessageBox.alert("Failed", response.responseText);
},
timeout: '10000'
});
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Search User</title>
</head>
<body>
#(Html.X().ResourceManager())
#(X.Panel()
.Layout(LayoutType.Border)
.Width(780)
.Height(460)
.Items(
X.TreePanel()
.Title("Department")
.ID("theTree")
.Region(Region.West)
.Width(250)
.Height(460)
.Border(false)
.Split(true)
.UseArrows(true)
.Listeners(l => l.ItemClick.Fn = "selectNode")
.Store(
Html.X().TreeStore()
.Proxy(
Html.X().AjaxProxy().Url(Url.Action("GetDepartmentChildren"))
)
)
.Root(
Html.X().Node().NodeID("0").Text(ViewBag.OrganizationName)
),
Html.X().GridPanel()
.ID("theGrid")
.Title("User Information")
.Region(Region.Center)
.Width(530)
.Height(460)
.Border(false)
.Store(Html.X().Store()
.AutoLoad(false)
.Model(Html.X().Model()
.Fields(
new ModelField("FirstName", ModelFieldType.String),
new ModelField("LastName", ModelFieldType.String),
new ModelField("Email", ModelFieldType.String)
)
)
//.DataSource(Model)
.Reader(reader => reader.Add(Html.X().JsonReader().Root("data")))
)
.ColumnModel(
Html.X().Column()
.Text("First Name")
.DataIndex("FirstName")
.Flex(1),
Html.X().Column()
.Text("LastName")
.DataIndex("LastName")
.Width(70)
.Align(Alignment.Center),
Html.X().Column()
.Text("Email")
.DataIndex("Email")
.Width(140)
)
.View(Html.X().GridView().StripeRows(true).TrackOver(true))
)
)
</body>
</html>
Here is JSON result data
{
"success":true,
"total":2,
"data":"[
{
\"FirstName\":\"BlahBlah1\",
\"LastName\":\"Kwak\",
\"Email\":\"BlahBlah1#hotmail.com\"
},
{
\"FirstName\":\"BlahBlah2\",
\"LastName\":\"Kwak\",
\"Email\":\"BlahBlah1#hotmail.com\"
}
]"
}

I found that loadData method reads only Model record data.
So, I fixed it by using loadRawData method instead loadData.

Related

How to set the data of chart in angular which is taken from the backend nodejs api that is store in mongodb and showing on the html page

app.component.html
This is my app.component file where i show my chart
<div style="display: block;">
<canvas baseChart width="400" height="400"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType">
</canvas>
</div>
app.component.ts
My ts file where the logic impleneted i have issue there i am not know how to perform logic to show the data i have issue how to create method in it which will call in the app.component.html file
constructor(private chartService: ChartServiceService) { }
ngOnInit(): void {
this.getlinechart();
}
getlinechart(){
this.chartService.getLineChart().subscribe(res => {
this.linechart = res;
console.log(res);
let lincechartData = res.list[0].data;
let lincechartLabels = res.list[0].graphlabels;
public lineChartData:any = this.lincechartData;
**I,m facing issue here above to create method to store the
data and used in html compiler give the error this ,'
expected.ts(1005)
Cannot find name 'lineChartData'**
});
}
app.service.ts
This is service file which getting the data from the backend nodejs api
getLineChart(){
return this.httpClient.get<any>
('http://localhost:3000/api/chart/line')
.pipe(
map(result => result)
)
}
If i undestand correctly you are trying to read data from a database and put it on a chart. I did something similar, but i had a bit different approach:
HTML:
<canvas id="myChart" width="300" height="100"></canvas> <br/>
Chart config:
var config = {
type: 'line',
data: { datasets: [] }, // trend data goes here
options: {
scales: {
xAxis: { // x axis
type: 'time',
}
},
},
}
New chart:
function newChart() {
config.data.datasets = []; // reset data
populateTrend(config); // populate chart
if (window.hasOwnProperty("graph")) { // destroy previous chart
if (typeof window.graph.resetZoom !== "undefined") { // if you have a zoom plugin
window.graph.resetZoom();
}
window.graph.destroy();
}
let ctx = document.getElementById('myChart').getContext('2d'); // canvas
window.graph = new Chart(ctx, config); // make the chart
}
populate trend:
function populateTrend (config) {
// data sets and scales
let datasets = config.data.datasets, scales = config.options.scales;
let log = data; // this is where you read from your database
let dataset = { // add some data here
data: [],
label: log.description,
fill: false,
radius: 0,
unit: log.unit,
pointType: log.pointType,
yAxisID: log.unit, // y axis
};
// this is where the real data goes
// you should push the data in a loop
dataset.data.push({
"x": something.getTime(),
"y": null,
"ymin": null,
"ymax": null,
});
datasets.push(dataset); // add data set to config
}

SharePoint online show or hide columns multiple fields required with same functionality

I'm working on the SharePoint online form with show or hide columns with the below code. it is working well but not able to combine three codes together and on the edit item form by default all the fields are getting hide even though as per the code it should show the fields based on selected dropdown value. if we change the values in the edit form again the show values are working fine.
along with this code i want the make all the visible fields are mandate fields with, any assistance would be really appreciated.
<script src="/sites/XXXXXX/XXXXXXXX/SiteAssets/jquery-1.7.2.min%20-%20Show%20or%20Hide.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('nobr:contains("Person1")').closest('tr').hide();
$('nobr:contains("Person2")').closest('tr').hide();
$('nobr:contains("Dropdown")').closest('tr').hide();
$('nobr:contains("Dropdown1")').closest('tr').hide();
$('nobr:contains("Text")').closest('tr').hide();
$('nobr:contains("Dropdown2")').closest('tr').hide();
$('nobr:contains("Date column")').closest('tr').hide();
$('nobr:contains("Number filed")').closest('tr').hide();
$('nobr:contains("Dropdown3")').closest('tr').hide();
$('nobr:contains("Remarks")').closest('tr').hide();
$('nobr:contains("Dropdown4")').closest('tr').hide();
$('nobr:contains("number2)")').closest('tr').hide();
$('nobr:contains("Dropdown5")').closest('tr').hide();
$('nobr:contains("Dropdown6")').closest('tr').hide();
$("select[title='Status Required Field']").change(function () {
console.log("selection changed", $("[title='Status Required Field'] option:selected").text());
alert($("[title='Status Required Field'] option:selected").text());
if ($("[title='Status Required Field'] option:selected").text() != "submitted") {
$('nobr:contains("Person1")').closest('tr').hide();
$('nobr:contains("Person2")').closest('tr').hide();
$('nobr:contains("Dropdown")').closest('tr').hide();
$('nobr:contains("Dropdown1")').closest('tr').hide();
$('nobr:contains("Text")').closest('tr').hide();
$('nobr:contains("Dropdown2")').closest('tr').hide();
$('nobr:contains("Date column")').closest('tr').hide();
$('nobr:contains("Number filed")').closest('tr').hide();
$('nobr:contains("Dropdown3")').closest('tr').hide();
$('nobr:contains("Remarks")').closest('tr').hide();
$('nobr:contains("Dropdown4")').closest('tr').hide();
$('nobr:contains("number2")').closest('tr').hide();
$('nobr:contains("Dropdown5")').closest('tr').hide();
$('nobr:contains("Dropdown6")').closest('tr').hide();
}
else {
$('nobr:contains("Person1")').closest('tr').show();
$('nobr:contains("Person2")').closest('tr').show();
$('nobr:contains("Dropdown")').closest('tr').show();
$('nobr:contains("Dropdown1")').closest('tr').show();
$('nobr:contains("Text")').closest('tr').show();
$('nobr:contains("Dropdown2")').closest('tr').show();
$('nobr:contains("Date column")').closest('tr').show();
$('nobr:contains("Number filed")').closest('tr').show();
$('nobr:contains("Dropdown3")').closest('tr').show();
$('nobr:contains("Remarks")').closest('tr').show();
$('nobr:contains("Dropdown4")').closest('tr').show();
}
});
});
</script>
<script src="/sites/XXXXXX/XXXXXXXX/SiteAssets/jquery-1.7.2.min%20-%20Show%20or%20Hide.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('nobr:contains("number2")').closest('tr').hide();
$('nobr:contains("Dropdown5")').closest('tr').hide();
$('nobr:contains("Dropdown6")').closest('tr').hide();
$("select[title='Dropdown4']").change(function () {
console.log("selection changed", $("[title='Dropdown4'] option:selected").text());
alert($("[title='Dropdown4'] option:selected").text());
if ($("[title='Dropdown4'] option:selected").text() != "Active") {
$('nobr:contains("number2")').closest('tr').hide();
$('nobr:contains("Dropdown5")').closest('tr').hide();
$('nobr:contains("Dropdown6")').closest('tr').hide();
}
else {
$('nobr:contains("number2")').closest('tr').show();
$('nobr:contains("Dropdown5")').closest('tr').show();
}
});
});
</script>
<script src="/sites/XXXXXX/XXXXXXXX/SiteAssets/jquery-1.7.2.min%20-%20Show%20or%20Hide.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('nobr:contains("Dropdown6")').closest('tr').hide();
$("select[title='Dropdown5").change(function () {
console.log("selection changed", $("[title='Dropdown5'] option:selected").text());
alert($("[title='Dropdown5'] option:selected").text());
if ($("[title='Dropdown5'] option:selected").text() != "Yes") {
$('nobr:contains("Dropdown6")').closest('tr').hide();
}
else {
$('nobr:contains("Dropdown6")').closest('tr').show();
}
});
});
</script>```
As far as fields hidden on Edit form your document ready function is hiding the fields. There are alot of ways to get the form state. You can simply check location contains New ,Display or Edit form and hide your fields accordingly.
var isNewMode = document.location.pathname.indexOf("/NewForm.aspx") > -1;
var isDisplayMode = document.location.pathname.indexOf("/DispForm.aspx") > -1;
var isEditMode = document.location.pathname.indexOf("/EditForm.aspx") > -1;
if(isNewMode)
{
alert("New");
}
if(isDisplayMode)
{
alert("Display");
}
if( isEditMode)
{
alert("Edit");
}
You can use PreSaveAction() function to do your custom validation. This function is executed once you click on the submit button. return true to submit the form or else return false to stay in the same page.
For Validation Add the code as follows:
function PreSaveAction(){
if($('nobr:contains("someid")').val() == ''){
alert('Required field'); // some custom validation
return false;
}else{
return true;
}
}

Why is my tabulator custom header filter changing on keyup?

To reproduce:
Run the Code Snippet (recommend Full Page mode)
Hold Ctrl or Shift while clicking to select multiple 'species' in the table column header
Note that while the key is held down, the table data is filtered according to selected 'species'
Release the key, observe changes in filtered table data
I think this is probably related to https://github.com/olifolkerd/tabulator/issues/975 and that I need to do something to override default tabulator keypress events.
JSFiddle: https://jsfiddle.net/jjech/3th28pv0/229/
const speciesTypes = [ 'Human', 'Android', 'Betazoid', 'Klingon', 'Ferengi', 'Tamarian' ];
function multiSelectHeaderFilter(cell) {
var values = speciesTypes;
const filterFunc = (rowData) => {
return values.includes(rowData['species']);
}
const getSelectedValues = (multiSelect) => {
var result = [];
var options = multiSelect && multiSelect.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
const onChange = () => {
var editor = document.getElementById('speciesSelector');
values = getSelectedValues(editor);
console.log("values: "+values);
cell.getColumn().getTable().removeFilter(filterFunc);
cell.getColumn().getTable().addFilter(filterFunc);
}
var select = document.createElement("select");
select.multiple = "multiple";
select.id = 'speciesSelector';
select.style = 'width: 100%';
speciesTypes.forEach(species => {
select.innerHTML += "<option id='"+species+"' value='"+species+"' selected='selected'>"+species+"</option>";
});
cell.getColumn().getTable().addFilter(filterFunc);
select.addEventListener('change',onChange);
return select;
}
var table = new Tabulator("#tabulator", {
layout:"fitColumns",
data:[ {name:'Geordi La Forge',species:'Human'}, {name:'Dathon', species:'Tamarian'}, {name:'Jean-Luc Picard', species:'Human'}, {name:'Worf, son of Mogh', species:'Klingon'}, {name:'Tasha Yarr', species:'Human'}, {name:'Data', species:'Android'}, {name:'Wesley Crusher', species:'Human'}, {name:'Jalad', species:'Tamarian'}, {name:'Lwaxana Troi', species:'Betazoid'}, {name:'Temba', species:'Tamarian'}, {name:'T\'Kuvma', species:'Klingon'}, {name:'Lore', species:'Android'}, {name:'Noonian Soongh', species:'Human'}, {name:'Darmok', species:'Tamarian'}, {name:'Reittan Grax', species:'Betazoid'}, {name:'Quark', species:'Ferengi'} ],
headerSort:true,
columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter }, ],
});
//document.multiselect('#speciesSelector');
<html>
<head>
<link href="https://unpkg.com/tabulator-tables#4.5.3/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.5.3/dist/js/tabulator.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/mneofit/multiselect/styles/multiselect.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/mneofit/multiselect/multiselect.min.js"></script>
<script></script>
<style>
.tabulator .tabulator-header,
.tabulator .tabulator-header .tabulator-col
{
overflow: unset;
}
</style>
</head>
<body>
<div id="tabulator"></div>
</body>
</html>
Fixed by adding headerFilterLiveFilter:false to the column definition.
columns:[ {title:'Name',field:'name',sorter:'string'},{title:'Species',field:'species',sorter:'string',headerFilter:multiSelectHeaderFilter,headerFilterLiveFilter:false }, ],
https://jsfiddle.net/jjech/3th28pv0/237/

How to update paginated dgrid periodically

I am trying to display and refresh periodically some server data using dgrid and derivative of Request dstore. The data are paginated and needs to be updated periodically. As a first naive approach I tried to call Dgrid.refresh() with setInterval. However, that results in complete rebuilding of grid rows which visually creates flickering effect. Using Trackable to the store does not help. Can anyone advise me how to refresh rows in the dgrid which would only update changed rows?
Here is my code reproducing the issue:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DGrid flickering on slow updates</title>
<style>
#import "./dojo-release-1.11.1/dojo/resources/dojo.css";
#import "./dojo-release-1.11.1/dijit/themes/claro/claro.css";
#import "./META-INF/resources/webjars/dgrid/1.0.0/css/dgrid.css";
#import "./META-INF/resources/webjars/dgrid/1.0.0/css/skins/claro.css";
html, body {
padding: 10px;
width: 100%;
height: 100%;
}
</style>
<script>
var dojoConfig = {
async:true,
baseUrl: "./",
packages:[
{ name:"dojo", location:"dojo-release-1.11.1/dojo" },
{ name:"dijit", location:"dojo-release-1.11.1/dijit" },
{ name:"dgrid", location:"META-INF/resources/webjars/dgrid/1.0.0" },
{ name:"dstore", location:"META-INF/resources/webjars/dstore/1.1.1" }
]
};
</script>
<script src="dojo-release-1.11.1/dojo/dojo.js"></script>
<script>
require(["dojo/parser",
"dojo/dom",
"dojo/_base/declare",
"dstore/Store",
"dstore/Trackable",
"dstore/Cache",
"dstore/Memory",
"dstore/QueryResults",
"dojo/Deferred",
"dgrid/Grid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/extensions/Pagination",
"dojo/domReady!"],
function(parser, dom, declare, Store, Trackable, Cache, Memory, QueryResults, Deferred, Grid, Keyboard, Selection, Pagination)
{
parser.parse();
console.log("Parsed");
var makeSlowRequest =
function(kwArgs)
{
var responseDeferred = new Deferred();
var responsePromise = responseDeferred.promise;
// resolve promise in 2 seconds to simulate slow network connection
setTimeout(function ()
{
console.log("Generating response");
var data = {items: [], total: 100};
kwArgs = kwArgs || {start:0, end:100};
for(var i = kwArgs.start; i < kwArgs.end; i++)
{
data.items.push({id: "id-" + i,
name: "test-" + i,
value: Math.floor((Math.random() * 10) + kwArgs.start)
});
}
responseDeferred.resolve(data);
}, 2000);
return new QueryResults(responsePromise.then(function (data) { return data.items; }),
{ totalLength: responsePromise.then(function (data) { return data.total;}) });
};
var SlowStore = declare("SlowStore",
[Store, Trackable],
{ fetch: function (kwArgs) { return makeSlowRequest(kwArgs); },
fetchRange: function (kwArgs) { return makeSlowRequest(kwArgs); }
});
var store = new SlowStore();
var TestGrid = declare([Grid, Keyboard, Selection, Pagination]);
var grid = new TestGrid({
collection: store,
columns: {name: "Name", value: "Value"},
rowsPerPage: 10,
selectionMode: 'single',
cellNavigation: false,
className: 'dgrid-autoheight',
pageSizeOptions: [10, 20],
adjustLastColumn: true
}, dom.byId("grid"));
grid.startup();
// update grid every 5 seconds
var timer = setInterval(function(){console.log("Refreshing grid"); grid.refresh();}, 5000);
});
</script>
</head>
<body class="claro">
<div id="grid"></div>
</body>
</html>
I am guessing that instead of calling refresh I need get the request range from the dgrid (possibly using aspect on gotoPage) and call store.fetchRange(), iterate over the results, compare each item with previous results and invoke store.update or store.add or store.delete. I suppose that would give me what I want but before taking this approach I wondering if there is an easier way to refresh dgrid with updated data. Using Cache store does not work as it expects to fetch all the data from the server:
var store = Cache.create(new SlowStore(), {
cachingStore: new (Memory.createSubclass(Trackable))()
});

YUI3 Datatable loaded with JSON displays only no results to display (Scala/Play 2.1)

I am new to YUI but I veteran of JQuery UI. So this one has me stumped. I cannot get my Datatable to render with the Rest service. I have two version of the code. One that I use the captured JSON object from the service as just a data object and a local datasource. That one works fine. When I attempt to switch to the GET plugin and get it from the service. It just never renders.
My local example:
#main("Play 2.1") {
<script type="text/javascript">
YUI().use("datatable", "datasource-local", "datasource-jsonschema", "datatable-datasource", function (Y) {
var data = [
{"script":{"id":34534,
"scriptText":"234523452345234",
"modifiedDate":1367525647000,
"status":"Reviewed",
"qcDate":1367526006000,
"location":{"id":1},
"orderInfo":{"id":1,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}},
{"script":{"id":656435,
"scriptText":"36536543636365",
"modifiedDate":1367525646000,
"status":"Reviewed",
"qcDate":1367526017000,
"location":{"id":1},
"orderInfo":{"id":43534534,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}}
];
var localDataSource = new Y.DataSource.Local({source:data});
localDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema:{
resultListLocator:"",
resultFields:[
{
key:"id",
locator:"script.id"
},
{
key:"scriptText",
locator:"script.scriptText"
},
{
key:"modifiedDate",
locator:"script.modifiedDate"
}
]
}
});
var simple = new Y.DataTable({
columns:["id", "scriptText", "modifiedDate"],
summary:"Example Summary",
caption:"Example Caption"
});
simple.plug(Y.Plugin.DataTableDataSource, {
datasource:localDataSource
});
simple.render("#dataGrid");
simple.datasource.load();
});
</script>
<span id="listView">
<div id="dataGrid" style="height: 95%;width: 100%;"></div>
</span>
<div id="dataCheckArea">
<h3>RAW DATA AREA</h3>
<ul>
#records.map {record =>
<li>#record.toString</li>
}
</ul>
</div>
}
My REST Service example:
#main("Welcome to Play 2.1") {
<script type="text/javascript">
YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", function (Y) {
var dataSource = new Y.DataSource.Get({
source:"http://localhost:9000/reviewRecords?q=query"
});
dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema:{
resultListLocator:"",
resultFields:[
{
key:"id",
locator:"script.id"
},
{
key:"scriptText",
locator:"script.scriptText"
},
{
key:"modifiedDate",
locator:"script.modifiedDate"
}
]
}
});
var dataGrid = new Y.DataTable({
columns:["id", "scriptText", "modifiedDate"],
summary:"Example Summary",
caption:"Example Caption"
});
dataGrid.plug(Y.Plugin.DataTableDataSource, { datasource:dataSource });
dataGrid.render("#dataGrid");
dataGrid.datasource.load();
});
</script>
<span id="listView">
<div id="dataGrid" style="height: 95%;width: 100%;"></div>
</span>
** edited because the original submission lost my second code block.
The problem wasn't with my javascript code. The issue was with how I was sending the response. The YUI framework expects that the response will be wrapped in a callback function. When I changed my response to give a JSONP response with the callback it all started working.
YUI.Env.DataSource.callbacks.yui_3_11_0_1_1379097239018_187([
{"script":{"id":34534,
"scriptText":"234523452345234",
"modifiedDate":1367525647000,
"status":"Reviewed",
"qcDate":1367526006000,
"location":{"id":1},
"orderInfo":{"id":1,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}},
{"script":{"id":656435,
"scriptText":"36536543636365",
"modifiedDate":1367525646000,
"status":"Reviewed",
"qcDate":1367526017000,
"location":{"id":1},
"orderInfo":{"id":43534534,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}}
])
I did this by using a JSONP call in the method response from Scala/Play 2.1
def reviewRecords(q: String, callback: String) = Action {
val reviewRecords = reviewRecordsService.currentReviewRecords
Ok(new Jsonp(callback, Json.toJson(DataTablesReturnObject(reviewRecords.size, reviewRecords.toArray)))).as("application/json")
}
I am going to edit the title of my original question to include the keywords for Play 2.1 and Scala because this ends up being a little different than a Java response.

Resources