Lazy High Charts: Chart not rendering in view - javascript

The div is appearing in the HTML, and the javascript also appears in the source... Any idea why I am still seeing nothing on the page?
NOTE: Manually running the js in the console causes the chart to render just fine
View:
<%= high_chart("some_id", #chart) %>
Controller:
#chart = LazyHighCharts::HighChart.new('graph') do |f|
f.title(:text => "Population vs GDP For 5 Big Countries [2009]")
f.xAxis(:categories => ["United States", "Japan", "China", "Germany", "France"])
f.series(:name => "GDP in Billions", :yAxis => 0, :data => [14119, 5068, 4985, 3339, 2656])
f.series(:name => "Population in Millions", :yAxis => 1, :data => [310, 127, 1340, 81, 65])
f.yAxis [
{:title => {:text => "GDP in Billions", :margin => 70} },
{:title => {:text => "Population in Millions"}, :opposite => true},
]
f.legend(:align => 'right', :verticalAlign => 'top', :y => 75, :x => -50, :layout => 'vertical',)
f.chart({:defaultSeriesType=>"column"})
end
Result in page view:
<script type="text/javascript">
(function() {
var onload = window.onload;
window.onload = function(){
if (typeof onload == "function") onload();
var options = { "title": { "text": "Population vs GDP For 5 Big Countries [2009]" },"legend": { "align": "right","verticalAlign": "top","y": 75,"x": -50,"layout": "vertical" },"xAxis": { "categories": [ "United States","Japan","China","Germany","France" ] },"yAxis": [ { "title": { "text": "GDP in Billions","margin": 70 } },{ "title": { "text": "Population in Millions" },"opposite": true } ],"tooltip": { "enabled": true },"credits": { "enabled": false },"plotOptions": { "areaspline": { } },"chart": { "defaultSeriesType": "column","renderTo": "some_id" },"subtitle": { },"series": [{ "name": "GDP in Billions","yAxis": 0,"data": [ 14119,5068,4985,3339,2656 ] },{ "name": "Population in Millions","yAxis": 1,"data": [ 310,127,1340,81,65 ] }] };
window.chart_some_id = new Highcharts.Chart(options);
};
})()
</script>
<div id="some_id"></div>

Related

prebid.js ad is not getting rendered

I have setup prebid.js with single adaptor configured on test page. I am getting the ad response from adaptor and I can see the pbjs.getBidResponses() object is present still ad is not getting rendered on the page.
you can visit test page
standard prebid setup as follows
JAVSCRIPT
var sizes = [
[300, 250]
];
var PREBID_TIMEOUT = 1000;
var FAILSAFE_TIMEOUT = 3000;
var adUnits = [{
code: '/19968336/header-bid-tag-1',
mediaTypes: {
banner: {
sizes: sizes
}
},
bids: [{
bidder: 'incrementx',
params: {
placementId: 'PNX-HB-R787915V41024E'
}
}]
}];
// ======== DO NOT EDIT BELOW THIS LINE =========== //
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
googletag.cmd.push(function () {
googletag.pubads().disableInitialLoad();
});
var pbjs = pbjs || {};
pbjs.que = pbjs.que || [];
pbjs.que.push(function () {
pbjs.addAdUnits(adUnits);
pbjs.requestBids({
bidsBackHandler: initAdserver,
timeout: PREBID_TIMEOUT
});
});
function initAdserver() {
if (pbjs.initAdserverSet) return;
pbjs.initAdserverSet = true;
googletag.cmd.push(function () {
pbjs.setTargetingForGPTAsync && pbjs.setTargetingForGPTAsync();
googletag.pubads().refresh();
});
}
// in case PBJS doesn't load
setTimeout(function () {
initAdserver();
}, FAILSAFE_TIMEOUT);
googletag.cmd.push(function () {
googletag.defineSlot('/19968336/header-bid-tag-1', sizes, 'div-1')
.addService(googletag.pubads());
googletag.pubads().collapseEmptyDivs();
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
HTML
<div id='div-1'>
<script type='text/javascript'>
googletag.cmd.push(function () {
googletag.display('div-1');
});
</script>
</div>
ADAPTOR Response
{
"vzhPlacementId": "<placement-id>",
"bid": "<bid>",
"adWidth": "300",
"adHeight": "250",
"cpm": "0.017442",
"ad": "<ad-tag>",
"slotBidId": "<slot-id>",
"statusText": "Vertoz:Success"
}
pbjs.getBidResponses() output
{
"/19968336/header-bid-tag-1": {
"bids": [
{
"bidderCode": "incrementx",
"width": 300,
"height": 250,
"statusMessage": "Bid available",
"adId": "389575b4d6d5f1",
"requestId": "2b7446c2969f1f",
"transactionId": "a6a81b3e-8cf7-4d71-bc7e-34c283e1a746",
"auctionId": "4455d9a4-4364-4f9d-bd1a-d7f0a7fd56e4",
"mediaType": "banner",
"source": "client",
"cpm": 0.017442,
"currency": "USD",
"ttl": 300,
"creativeId": 0,
"netRevenue": false,
"meta": {
"mediaType": "banner",
"advertiserDomains": [],
"dchain": {
"ver": "1.0",
"complete": 0,
"nodes": [
{
"name": "incrementx"
}
]
}
},
"ad": "<ad-tag>",
"adapterCode": "incrementx",
"originalCpm": "0.017442",
"originalCurrency": "USD",
"responseTimestamp": 1656921876245,
"requestTimestamp": 1656921875927,
"bidder": "incrementx",
"adUnitCode": "/19968336/header-bid-tag-1",
"timeToRespond": 318,
"pbLg": "0.00",
"pbMg": "0.00",
"pbHg": "0.01",
"pbAg": "0.00",
"pbDg": "0.01",
"pbCg": "",
"size": "300x250",
"adserverTargeting": {
"hb_bidder": "incrementx",
"hb_adid": "389575b4d6d5f1",
"hb_pb": "0.00",
"hb_size": "300x250",
"hb_source": "client",
"hb_format": "banner",
"hb_adomain": ""
},
"status": "targetingSet"
}
]
}
}
pbjs.getAllPrebidWinningBids() & pbjs.getAllWinningBids() output
[]
this is the output I am getting
not able to find the issue, there is only 1 adaptor integrated so in all cases the bid should win, not sure am I missing something in setup?. Any help would be appreciated, thank you
Because this line is a copy from the prebid.org docs:
googletag.defineSlot('/19968336/header-bid-tag-1', sizes, 'div-1')
I don't think you have your own GAM account configured correctly.
You'll need to have a GAM account and switch the first parameter of defineSlot to be your own GAM ad unit code.
You'll want to follow the postbid instructions if you want to avoid using GAM.

Penetrate a JSON response by object value

I'm receiving following JSON response from our servers and my requirement is to display the servlet details.
if(dataStoreLogFileSize > 10 && "dataStoreLogLevel": "production".)
I have written following Javacript code snippet to penetrate the JSON by those values But it is not working properly. Can anyone help me with this please.
{
"web-app": {
"servlet": [{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm#pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreLogFileSize": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "production",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true,
"dataStoreInitConns": 10,
"dataStoreLogFileSize": 5,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "test",
"maxUrlLength": 500
}
}
],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
}
+********************************************************************************+
//Some code above
let foo = data.filter(object => (object.dataStoreLogLevel === 'production'
&& object => (object.dataStoreLogFileSize > '10');
console.log('Servlet Details Test' + foo);
//Code continues
You can use this code to get dataStoreLogFileSize greater than 1gb and production dataStoreLogLevel.
const jsoncode = {
"web-app": {
servlet: [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm#pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
templateProcessorClass: "org.cofax.WysiwygTemplate",
templateLoaderClass: "org.cofax.FilesTemplateLoader",
templatePath: "templates",
templateOverridePath: "",
defaultListTemplate: "listTemplate.htm",
defaultFileTemplate: "articleTemplate.htm",
useJSP: false,
jspListTemplate: "listTemplate.jsp",
jspFileTemplate: "articleTemplate.jsp",
searchEngineListTemplate: "forSearchEnginesList.htm",
searchEngineFileTemplate: "forSearchEngines.htm",
searchEngineRobotsDb: "WEB-INF/robots.db",
useDataStore: true,
dataStoreClass: "org.cofax.SqlDataStore",
redirectionClass: "org.cofax.SqlRedirection",
dataStoreName: "cofax",
dataStoreDriver: "com.microsoft.jdbc.sqlserver.SQLServerDriver",
dataStoreUrl:
"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
dataStoreUser: "sa",
dataStorePassword: "dataStoreTestQuery",
dataStoreTestQuery: "SET NOCOUNT ON;select test='test';",
dataStoreLogFile: "/usr/local/tomcat/logs/datastore.log",
dataStoreInitConns: 10,
dataStoreLogFileSize: "1GB",
dataStoreMaxConns: 100,
dataStoreConnUsageLimit: 100,
dataStoreLogLevel: "production",
maxUrlLength: 500
}
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
templatePath: "toolstemplates/",
log: 1,
logLocation: "/usr/local/tomcat/logs/CofaxTools.log",
logMaxSize: "",
dataLog: 1,
dataLogLocation: "/usr/local/tomcat/logs/dataLog.log",
dataLogMaxSize: "",
removePageCache: "/content/admin/remove?cache=pages&id=",
removeTemplateCache: "/content/admin/remove?cache=templates&id=",
fileTransferFolder:
"/usr/local/tomcat/webapps/content/fileTransferFolder",
lookInContext: 1,
adminGroupID: 4,
betaServer: true,
dataStoreInitConns: 10,
dataStoreLogFileSize: "0.5GB",
dataStoreMaxConns: 100,
dataStoreConnUsageLimit: 100,
dataStoreLogLevel: "test",
maxUrlLength: 500
}
}
],
"servlet-mapping": {
cofaxCDS: "/",
cofaxEmail: "/cofaxutil/aemail/*",
cofaxAdmin: "/admin/*",
fileServlet: "/static/*",
cofaxTools: "/tools/*"
},
taglib: {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
};
// jsoncode is your json response from server
const final = jsoncode['web-app'].servlet.filter((s) => {
// get the number from dataStoreLogFileSize
const size = s['init-param'].dataStoreLogFileSize.replace(/[^0-9\.]+/g, '');
// make sure the size is a number by adding a plus sign
return +size >= 1 && s['init-param'].dataStoreLogLevel === 'production';
});
console.log(final);
you're filtering the wrong array, the one having dataStoreLogLevel and dataStoreLogFileSize is in data['web-app'][0]['servlet']['init-param'], so you need to apply .filter on the data['web-app'].servlet array.
For the fileSize you'll need to use parseFloat to extract the size since it's a string.
You need to fix the .filter syntax.
and use , to console.log the result :
const data = {
"web-app": {
"servlet": [{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm#pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreLogFileSize": "1GB",
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "production",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true,
"dataStoreInitConns": 10,
"dataStoreLogFileSize": "0.5GB",
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "test",
"maxUrlLength": 500
}
}
],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
}
let foo = data['web-app'].servlet.filter(
object =>
object['init-param'].dataStoreLogLevel === 'production'
&& parseFloat(object['init-param'].dataStoreLogFileSize) >= 1 // change this to 10 for fileSize >= 10GB
);
console.log('Servlet Details Test', foo);

Manually convert from XML view to Javascript view in sapui5

The documentation at https://sapui5.hana.ondemand.com/#/controls provides many SAPUI5 samples. But all the views are written in XML. I can find examples written in Javascript elsewhere but I'm asking for a general rule to apply on XML code. Here is an example List.view.xml wich I need to manually convert to List.view.js
<mvc:View
height="100%"
controllerName="sap.m.sample.ListSelectionSearch.List"
xmlns:l="sap.ui.layout"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">
<Page
showHeader="false" >
<subHeader>
<Toolbar>
<SearchField
liveChange="onSearch"
width="100%" />
</Toolbar>
</subHeader>
<content>
<List
id="idList"
items="{/ProductCollection}"
selectionChange="onSelectionChange"
mode="MultiSelect"
includeItemInSelection="true" >
<infoToolbar>
<Toolbar
visible="false"
id="idInfoToolbar" >
<Label id="idFilterLabel" />
</Toolbar>
</infoToolbar>
<items>
<StandardListItem
title="{Name}"
description="{ProductId}"
icon="{ProductPicUrl}"
iconDensityAware="false"
iconInset="false" />
</items>
</List>
</content>
</Page>
Any help will be appreciated.
Here is the same in SAPUI5's JSView with list aggregation done in the controller:
Alternatively, have a look at this full application Example SAPUI5 JSView Application
OR
Make use of the Diagnostic tool by pressing CTRL+SHIFT+ALT+S and API References
sap.ui.define(["sap/m/Page", "sap/m/List", "sap/m/Toolbar", "sap/m/SearchField", "sap/m/Label", "sap/m/Text"], function(Page, List, Toolbar, SearchField, Label, Text) {
"use strict";
return sap.ui.jsview("sap.m.sample.ListSelectionSearch.View", {
getControllerName: function() {
return "sap.m.sample.ListSelectionSearch.List";
},
createContent: function(oController) {
var oToolbar = new Toolbar({
visible: true,
content: [
new SearchField({
liveChange: function() {
oController.onSearch();
},
width: "100%"
})
]
});
var oInfoToolbar = new Toolbar({
content: new Toolbar(this.createId("idInfoToolbar"), {
visible: true,
content: new Text({
text: "Label Text"
})
})
});
var oList = new List(this.createId("idList"), {
mode: "MultiSelect",
includeItemInSelection: true,
infoToolbar: oInfoToolbar
});
var oPage = new Page(this.createId("oPageId"), {
height: "100%",
title: "Page Title",
showHeader: true,
showSubHeader: true,
headerContent: oToolbar,
content: [oList]
});
var app = new sap.m.App();
app.addPage(oPage);
app.placeAt("content");
return app;
}
});
});
//in Controller
sap.ui.define(["sap/m/StandardListItem", "sap/ui/model/json/JSONModel"], function(StandardListItem, JSONModel) {
"use strict";
var oData = {
"ProductCollection": [{
"titleId": 0,
"Name": "Olayinka Otuniyi",
"ProductId": "001",
"ProductPicUrl": "sap-icon://competitor"
}, {
"titleId": 1,
"Name": "Maria Anders",
"ProductId": "002",
"ProductPicUrl": "sap-icon://badge"
}, {
"titleId": 2,
"Name": "Ana Trujillo",
"ProductId": "003",
"ProductPicUrl": "sap-icon://broken-link"
}, {
"titleId": 3,
"Name": "Thomas Hardy",
"ProductId": "004",
"ProductPicUrl": "sap-icon://create"
}, {
"titleId": 4,
"Name": "Christina Berglund",
"ProductId": "005",
"ProductPicUrl": "sap-icon://pending"
}, {
"titleId": 5,
"Name": "Hanna Moos",
"ProductId": "006",
"ProductPicUrl": "sap-icon://decision"
}, {
"titleId": 6,
"Name": "Martín Sommer",
"ProductId": "007",
"ProductPicUrl": "sap-icon://process"
}, {
"titleId": 7,
"Name": "Laurence Lebihans",
"ProductId": "008",
"ProductPicUrl": "sap-icon://accept"
}, {
"titleId": 8,
"Name": "Elizabeth Lincoln",
"ProductId": "009",
"ProductPicUrl": "sap-icon://alert"
}]
};
return sap.ui.controller("sap.m.sample.ListSelectionSearch.List", {
// onInit: function() {
// },
onAfterRendering: function() {
var oModel = new JSONModel(oData);
this.getView().setModel(oModel, "products");
var oTemplate = new StandardListItem({
title: "{products>Name}",
description: "{products>ProductId}",
icon: "{products>ProductPicUrl}",
iconDensityAware: false,
iconInset: false,
type: "Active"
});
oTemplate.attachPress(this.onSelectionChange, this);
this.getView().byId("idList").bindItems({
path: "/ProductCollection",
template: oTemplate,
model: "products"
});
},
onSearch: function() {
console.log("Searching");
},
onSelectionChange: function() {
console.log("changing Selection");
}
});
});
Should not be that difficult:
new sap.m.Page({
showHeader: false,
subHeader: new sap.m.Toolbar({
content: [ // (**)
new sap.m.SearchField({
liveChange: onSearch, // event handler
width: "100%"
})
]
}),
content: [
new sap.m.List({
//...
})
]
});
OR you can keep writing XML and then create JS instances from it using API:
sap.ui.xmlfragment
sap.ui.xmlview
(**) here is probably the trickiest part. How could you know that this should be wrapped inside "content" property? Very easy! If you see one control inside another directly (without any tags around it), it means inner control is in default aggregation of parent control. So, all you need to do is check what is the name of the default aggregation of the parent control. In case of sap.m.Toolbar it's a content.
UPDATE: however, it might be difficult to understand which aggregation is default, because in our docs we do not show this information. I will contact responsible team on this matter. As a work around it's possible to get this information from the source code, e.g. sap.m.Page - see defaultAggregation definition in metadata description.
Please see the example below
View:
sap.ui.jsview("ResourceRootName.view.ViewName", {
getControllerName: function() {
return "ResourceRootName.view.ViewName";
},
createContent : function(oController) {
this.oList = new sap.m.List({
showUnread: true,
mode: sap.ui.Device.system.phone ? sap.m.ListMode.None : sap.m.ListMode.SingleSelectMaster,
itemPress: [oController.onListSelect, oController]
});
this.page = new sap.m.Page({
title: "{i18n>pageTitle}",
navButtonText: "Home",
showNavButton: true,
navButtonPress: function() {
oController.handleNavBack();
},
subHeader: new sap.m.Bar({
contentMiddle: [
new sap.m.SearchField(oController.createId("searchFieldTasks"), {
width: "100%"
})
]
}),
content: [this.oList]
});
return this.page; //Note: if you need to return more than two controls you can do so by using array
}
});
In controller you can bind your list as below
Controller:
this.getView().oList.bindAggregation("items", {
path: "/EntityCollectionSet",
template: new sap.m.StandardListItem({
title: "{Title}",
description: "{Description}"
}),
filters: []//If you want to pass any filters
});

Kendo Grid sometimes renders only title or data

I have a pretty simple Kendo Grid that displays a list of data with titles and is conditionally editable on a field. This is rendered and attached to the DOM using JQuery in a function that is called in the "show" action of a Kendo View.
The issue is that either the data does not render or the grid column headers don't render every time I load the page. It's always one or the other, the only time it renders properly is if I refire the function that attaches it as I occasionally do when the state of the page changes.
Here's where I attach it to the page:
form.find("#approvals").kendoGrid({
columns: [
{ title: "Service", field: "PartDescription" },
{ title: "Component", field: "Component", width: "250px" },
{ title: "Status Last Modified", width: "250px", template: "#= kendo.toString(StatusModifiedDate, 'g') #", },
{ title: "Status", field: "Status", width: "135px", editor: statusDropDownEditor }
],
editable: modifyState,
edit: function (e) {
if (e.container.find("input").attr("name") !== "Status") {
this.closeCell();
}
}
});
This comes from the function that is fired when the Kendo View is shown.
The issue is that either the data does not render or the grid column
headers don't render every time I load the page.
Without knowing what "form" is in your js code, try using this to make sure it loads at the 'correct' time. Please feel free to tinker the gridData variable to match your code and preg_replace the fields for your fields.
<!DOCTYPE html>
<html>
<head>
<script src="https://kendo.cdn.telerik.com/2017.1.118/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
</head>
<body id="theBod">
<div id="approvals"></div>
<script type="text/javascript">
$(function () { // the dom is ready for jquery parsing
var gridData = [{
"Name": "daya",
"Role": "Developer",
"Dept": "Dev",
"Date": "\/Date(836438400000)\/",
"Balance": 23
}, {
"Name": "siva",
"Role": "Developer",
"Dept": "Dev",
"Date": "\/Date(836438400000)\/",
"Balance": 23
}, {
"Name": "sivadaya",
"Role": "Developer",
"Dept": "Dev",
"Date": "\/Date(836438400000)\/",
"Balance": 23
}, {
"Name": "dayasiva",
"Role": "Developer",
"Dept": "Dev",
"Date": "\/Date(836438400000)\/",
"Balance": 23
}];
var form = $("#theBod");
var foundForm = $(form).find("#approvals");
if (typeof (foundForm) != "undefined") {
// process grid component
var grid = $(foundForm).kendoGrid({
dataSource: {
data: gridData,
schema: {
model: {
fields: {
Name: { type: "string" },
Role: { type: "string" }
}
}
},
pageSize: 10,
},
editable: true,
sortable: true,
columns: [
{
field: "Name",
title: "Name",
},
{
field: "Role",
title: "TheRole"
}
]
});
} else {
alert('no dom element located');
}
});
</script>
</body>
</html>
I have added a jsBin file for you.
The jsBin was not saved correctly, apologies.

Create drilldown fusion chart on the same page

You will get results on the fusioncharts website if you search up what I asked, but it is not exactly what I am looking for.
I am querying data from a MySQL database, and putting this data into a fusion chart to display on my webpage. I want there to be 2 graphs on the same page, and when you click on one of the datapoints on the parent graph, the child graph will display the "drilled down" graph. How can I do this? As of right now I can press on the parent graph and it will open the child graph on a new webpage. This is the code for the home page with the parent graph. The file is named "dept.php".
<?php
/*Include the `fusioncharts.php` file that contains functions
to embed the charts.
*/
include("includes/fusioncharts.php");
// Establish a connection to the database. Variables defined before
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
// Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
// Form the SQL query that returns the top 10 most populous countries
$strQuery = "SELECT Department, SUM(Quantity) AS Quantity FROM Scrap GROUP BY Department ORDER BY Department";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Sample Chart",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Department"],
"value" => $row["Quantity"],
"link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart. Initialize this object using the FusionCharts PHP class constructor. The constructor is used to initialize
the chart type, chart id, width, height, the div id of the chart container, the data format, and the data source. */
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
And then here is the other page that contains the child graph. The file is named "deptDrillDown.php".
<?php
/* Include the `includes/fusioncharts.php` file that contains functions to embed the charts.*/
include("includes/fusioncharts.php");
// Establish a connection to the database. Variables defined earlier
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
/*Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect */
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- Include the `fusioncharts.js` file. This file is needed to render the chart. Ensure that the path to this JS file is correct. Otherwise, it may lead to JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
// Get the country code from the GET parameter
$countryCode = $_GET["Department"];
// Form the SQL query that returns the top 10 most populous cities in the selected country
$cityQuery = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = ? GROUP BY ScrapDate ORDER BY ScrapDate";
// Prepare the query statement
$cityPrepStmt = $dbhandle->prepare($cityQuery);
// If there is an error in the statement, exit with an error message
if($cityPrepStmt === false) {
exit("Error while preparing the query to fetch data from City Table. ".$dbhandle->error);
}
// Bind the parameters to the query prepared
$cityPrepStmt->bind_param("s", $countryCode);
// Execute the query
$cityPrepStmt->execute();
// Get the results from the query executed
$cityResult = $cityPrepStmt->get_result();
// If the query returns a valid response, prepare the JSON string
if ($cityResult) {
/* Form the SQL query that will return the country name based on the country code. The result of the above query contains only the country code.
The country name is needed to be rendered as a caption for the chart that shows the 10 most populous cities */
$countryNameQuery = "SELECT ScrapDate FROM Scrap WHERE Department = ?";
// Prepare the query statement
$countryPrepStmt = $dbhandle->prepare($countryNameQuery);
// If there is an error in the statement, exit with an error message
if($countryPrepStmt === false) {
exit("Error while preparing the query to fetch data from Country Table. ".$dbhandle->error);
}
// Bind the parameters to the query prepared
$countryPrepStmt->bind_param("s", $countryCode);
// Execute the query
$countryPrepStmt->execute();
// Bind the country name to the variable `$countryName`
$countryPrepStmt->bind_result($countryName);
// Fetch the result from prepared statement
$countryPrepStmt->fetch();
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Top 10 Most Populous Cities in ".$countryName,
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = $cityResult->fetch_array()) {
array_push($arrData["data"], array(
"label" => $row["ScrapDate"],
"value" => $row["Quantity"]
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is `FusionCharts("type of chart",
"unique chart id", "width of chart", "height of chart", "div id to render the chart", "data format", "data source")`.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
// Close the database connection
$dbhandle->close();
}
?>
Back
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
n number of charts can be rendered in a single page using FusionCharts.
Store their chart references, e.g. in an associative array.
Use the dataplotClick event to capture the event being generated by clicking on a data.
Inside the callback, use the setJSONData to update the child chart, one wanna update.
A dummy code for this would be:
FusionCharts.ready(function () {
var chart1 = new FusionCharts({
type: 'msstackedcolumn2d',
renderAt: 'chart-container1',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
// enter the json data here
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
/* so every time a dataClickEvent is being triggered from the data plot,
a new json `json2` is fetched from a sql query and
chart2 is updated with it.*/
chart2.setJSONData(json2);
}
}
}
}).render();
});
Couple of days back I created this fiddle, hope this becomes useful here too. Instead of doing a SQL query, here we have a generalised data, every time a click is made, it internally makes a function call, and creates a data dynamically out of it. Lot of function calls for making it entirely dynamic might make the code look complex. But the basic philosophy I shared in the dummy code avobe is the same here.
The snippet version for the code for a quick reference.Better to run the result in full page to check whats exactly happening.
function getData() {
var arr = [{
seriesname: "Book A",
data: [{
"label": "Paper",
"value": 100
}, {
"label": "Promotion",
"value": 150
}, {
"label": "Transportation",
"value": 175
}, {
"label": "Royality",
"value": 200
}, {
"label": "Printing",
"value": 250
}, {
"label": "Binding",
"value": 275
}]
}, {
seriesname: "Book B",
data: [{
"label": "Paper",
"value": 130
}, {
"label": "Promotion",
"value": 110
}, {
"label": "Transportation",
"value": 155
}, {
"label": "Royality",
"value": 250
}, {
"label": "Printing",
"value": 210
}, {
"label": "Binding",
"value": 215
}]
}, {
seriesname: "Book C",
data: [{
"label": "Paper",
"value": 70
}, {
"label": "Promotion",
"value": 180
}, {
"label": "Transportation",
"value": 125
}, {
"label": "Royality",
"value": 150
}, {
"label": "Printing",
"value": 290
}, {
"label": "Binding",
"value": 245
}]
}, {
seriesname: "Book D",
data: [{
"label": "Paper",
"value": 150
}, {
"label": "Promotion",
"value": 100
}, {
"label": "Transportation",
"value": 105
}, {
"label": "Royality",
"value": 125
}, {
"label": "Printing",
"value": 278
}, {
"label": "Binding",
"value": 235
}]
}, {
seriesname: "Book E",
data: [{
"label": "Paper",
"value": 60
}, {
"label": "Promotion",
"value": 250
}, {
"label": "Transportation",
"value": 115
}, {
"label": "Royality",
"value": 189
}, {
"label": "Printing",
"value": 190
}, {
"label": "Binding",
"value": 285
}]
}, {
seriesname: "Book F",
data: [{
"label": "Paper",
"value": 190
}, {
"label": "Promotion",
"value": 200
}, {
"label": "Transportation",
"value": 160
}, {
"label": "Royality",
"value": 148
}, {
"label": "Printing",
"value": 178
}, {
"label": "Binding",
"value": 295
}]
}];
return arr;
}
function getValues(componentName) {
var i,
j,
arr = getData(),
valueArr = [],
len1;
for (i = 0, len = arr.length; i < len; i += 1) {
for (j = 0, len1 = arr[i].data.length; j < len1; j += 1) {
if (arr[i].data[j].label === componentName) {
valueArr.push({
value: arr[i].data[j].value
});
break;
}
}
}
return [{
seriesname: componentName,
data: valueArr
}];
}
function getProducts(componentName) {
var arr = getData(),
productArr = [];
for (i = 0, len = arr.length; i < len; i += 1) {
for (j = 0; j < arr[i].data.length; j += 1) {
if (arr[i].data[j].label === componentName) {
productArr.push({
"label": arr[i].seriesname,
"value": arr[i].data[j].value
});
break;
}
}
}
return productArr;
}
function getComponents(label, value) {
var arr = getData(),
sum,
i,
j,
len,
len1,
obj =
componentArr = [];
if (label === undefined) {
label = true;
}
if (value === undefined) {
value = true;
}
for (i = 0, len = arr[0].data.length; i < len; i += 1) {
sum = 0;
obj = {};
for (j = 0, len1 = arr.length; j < len1; j += 1) {
sum += arr[j].data[i].value;
}
if (label) {
obj.label = arr[0].data[i].label;
}
if (value) {
obj.value = sum;
}
componentArr.push(obj);
}
return componentArr;
}
function getSeriesNames() {
var arr = getData(),
seriesName = [];
for (i = 0, len = arr.length; i < len; i += 1) {
seriesName.push({
"label": arr[i].seriesname
});
}
return seriesName;
}
function getMode() {
var e = document.getElementById("interaction");
return e.options[e.selectedIndex].value;
}
FusionCharts.ready(function() {
var lastClickedId = true;
var pieChart = new FusionCharts({
type: 'pie2d',
renderAt: 'pieContainer',
width: '600',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Expenditures Incurred in Publishing a Book",
"subCaption": "Component-wise BreakUp",
"enableMultiSlicing": "0",
"bgcolor": "FFFFFF",
"showvalues": "1",
"showpercentvalues": "1",
"showborder": "0",
"showplotborder": "0",
"showlegend": "1",
"legendborder": "0",
"legendposition": "bottom",
"enablesmartlabels": "1",
"use3dlighting": "0",
"showshadow": "0",
"legendbgcolor": "#CCCCCC",
"legendbgalpha": "20",
"legendborderalpha": "0",
"legendshadow": "0",
"legendnumcolumns": "3",
"palettecolors": "#f8bd19,#e44a00,#008ee4,#33bdda,#6baa01,#583e78"
},
"data": getComponents()
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
if (getMode() === 'pie') {
var json = stackedChart.getJSONData(),
categoryLabel = dataObj.categoryLabel;
json.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
json.categories[0].category = getSeriesNames();
json.dataset = getValues(dataObj.categoryLabel);
stackedChart.setJSONData(json);
}
}
}
}).render();
var stackedChart = new FusionCharts({
type: 'stackedBar2D',
renderAt: 'barContainer',
width: '600',
height: '400',
dataFormat: 'json',
dataSource: {
"chart": {
"bgcolor": "FFFFFF",
"outcnvbasefontcolor": "666666",
"caption": "Expenditures Incurred in Publishing a Book",
"subCaption": "Product-wise BreakUp",
"xaxisname": "Expenditures Cost",
"yaxisname": "Cost",
"numberprefix": "$",
"showvalues": "0",
"numvdivlines": "10",
"showalternatevgridcolor": "1",
"alternatevgridcolor": "e1f5ff",
"divlinecolor": "e1f5ff",
"vdivlinecolor": "e1f5ff",
"basefontcolor": "666666",
"tooltipbgcolor": "F3F3F3",
"tooltipbordercolor": "666666",
"canvasbordercolor": "666666",
"canvasborderthickness": "1",
"showplotborder": "1",
"plotfillalpha": "80",
"showborder": "0",
"legendbgcolor": "#CCCCCC",
"legendbgalpha": "20",
"legendborderalpha": "0",
"legendshadow": "0",
"legendnumcolumns": "3"
},
"categories": [{
"category": getComponents(true, false)
}],
"dataset": getData()
},
"events": {
"dataplotClick": function(eventObj, dataObj) {
if (getMode() === 'stackedBar') {
var JSON = pieChart.getJSONData(),
categoryLabel = dataObj.categoryLabel;
JSON.chart.subCaption = "BreakUp of " + categoryLabel + " in different product";
JSON.data = getProducts(categoryLabel);
pieChart.setJSONData(JSON);
pieChart.slicePlotItem(dataObj.datasetIndex);
}
}
}
}).render();
function resetFN() {
var json = pieChart.getJSONData();
json.chart.subCaption = "Component-wise BreakUp";
json.data = getComponents();
pieChart.setJSONData(json);
json = stackedChart.getJSONData();
json.chart.subCaption = "Product-wise BreakUp";
json.categories[0].category = getComponents(true, false);
json.dataset = getData();
stackedChart.setJSONData(json);
}
document.getElementById('reset').addEventListener('click', resetFN);
document.getElementById('interaction').addEventListener('change', resetFN);
});
h4 {
font-size: 20px;
margin-bottom: 10px
}
.intro {
margin: 0 auto;
background-color: #fff280;
padding: 15px
}
em {
font-style: italic
}
#interactionWrapper {
margin: 5px 10px;
}
button {
border: 1px solid #0b77bc;
background-color: #0d83ce;
color: #ffffff;
margin: 10px 0 0 15px;
padding: 5px 10px;
font-size: 14px;
cursor: pointer
}
.centerAlign {
text-align: center;
}
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<div class="intro">
<h4>Expenditures incurred while publishing books</h4>
<p><em>A company has 6 books to publish for this quater. The stacked chart shows component prices stacked as per different books. While the pie chart, shows the cumilative component price.</em></p>
<p>
<em>There are two interaction modes - namely "Interact in stacked chart" and "Interact in pie chart".On clicking in any plot on stacked chart, it shows the book-wise distribution of that component in the pie chart. Whereas on clicking the pie chart, for a component being clicked, it shows the book-wise distribution in the bar chart</em>
</p>
</div>
<div id="interactionWrapper">
<span>Interaction Mode:</span>
<span>
<select id="interaction">
<option value="stackedBar">Interact in stacked bar</option>
<option value="pie">Interact in the pie chart</option>
</select>
</span>
</div>
<div class="centerAlign">
<span id="barContainer">FusionCharts XT will load here!</span>
<span id="pieContainer">FusionCharts XT will load here!</span>
</div>
<button id="reset">Reset</button>

Categories