How to dinamically fill sap.m.Select with data? - javascript

I need to display some odata's data in a sap.m.Select but don't know why is not working, This is the code I have so far
var oModel = new sap.ui.model.json.JSONModel();
var data = [];
var sUrlCard = "odata's url";
var oDataModel = new sap.ui.model.odata.ODataModel(sUrlCard, true);
oDataModel.read("CardBrandCollectionSet", {
async: false,
success: function(oData, response) {
$.each(oData.results, function(i, val) {
data.push(val);
});
oModel.setData({
'card': data
});
sap.ui.getCore().setModel(oModel, "card");
},
error: function(oError) {
console.log(oError);
}
});
table where the select input is located
var oTable = new sap.m.Table({
mode: oMode,
columns: [
{
hAlign: 'Center',
header: new Text({
text: "Card"
})
}
]
});
Select input I need to fill with data
var oSelectMarca = new sap.m.Select({
items: {
path: "/card",
template: new sap.ui.core.ListItem({
key: '{Codcard}',
text: '{Descript}'
}),
templateShareable: true
},
selectedKey: '{Marca}'
});

The binding path of the select control is wrong:
sap.ui.getCore().setModel(oModel, "card"); // model is set at core with name as card
$.each(oData.results, function(i, val) {
data.push(val);
});
oModel.setData({
'card': data // setting data in an object with name as card
});
var oSelectMarca = new sap.m.Select({
items: {
path: "card>/card/", //Binding path model name along with array name
template: new sap.ui.core.ListItem({
key: '{card>Codcard}', // model name with property name
text: '{card>Descript}' // model name with property name
}),
templateShareable: true
},
selectedKey: '{card>Marca}' // model name with property name
});

fist of all you do not want to create your odata model like that, please specify it in your manifest:
in "sap.app" part:
"dataSources": {
"yourRemote": {
"uri": "YOUR_URI",
"type": "OData",
"settings": {
"odataVersion": "2.0"
}
}
}
in "sap.ui5" part:
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "YOUR_i18n"
}
},
"remoteModel": {
"dataSource": "yourRemote"
}
}
2nd you dont want to create controls in js, you do that in your xml files:
https://sapui5.hana.ondemand.com/#/topic/1409791afe4747319a3b23a1e2fc7064
https://blogs.sap.com/2018/05/01/why-do-we-use-xml-views-rather-js-views-in-sapui5/
in that your select needs to be bound like that:
<Select
id="anID"
valueState="{vsModel>/otherText}"
valueStateText="{i18n>someText}"
forceSelection="false"
items="{
path: 'remoteModel>/CardBrandCollectionSet',
sorter: {
path: 'Descript'
}
}">
<core:Item key="{remoteModel>Codcard}" text="{remoteModel>Descript}" />
</Select>

Related

disallow blank/empty cells in kendo grid

How could I disallow a cell in my kendo grid to be 'blank' or 'empty' rather... How could I replace all blank or empties with a 0..
I have a save button grabbing the values from my kendo grid such as below: Everything works fine EXCEPT, it is completely omitting my empty cells.. I want to keep them, just have a 0 value on them...
Save button: want to keep the empties with simply a 0 or N/A..
$('.' + chs).on('click', '#saveChanges', function(e) {
which = $(frm).attr("class");
let dataSource = $("#grid").data("kendoGrid").dataSource,
data = dataSource.data(),
changedModels = [];
if(dataSource.hasChanges) { // only saves cells/row that have been edited/changed, need to keep this
for(var i = 0; i < data.length; i++) {
if(data[i].dirty) { changedModels.push(data[i].toJSON()) }
}
}
let ds = JSON.stringify(changedModels);
$.ajax({
type: "POST",
url: "saveGrid",
dataType: "json",
data: {
id: which,
data: ds
},
success: function(result) {
console.log('yy');
},
error: function(result) {
console.log('nn');
}
});
});
This is my kendo grid initialized:
let dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/popGrid?id=" + which,
dataType: "json"
},
},
batch: true,
schema: {
data: "data",
model: {
id: id,
}
},
});
console.log(id);
$("#grid").kendoGrid({
dataSource: dataSource,
height: 600,
sortable: true,
autoBind: true,
nullable: true,
editable: {
createAt: "top"
},
change: function(e) {
let grid = $("#grid").data("kendoGrid");
let selectedItem = grid.dataItem(grid.select());
let val = selectedItem.id;
console.log(val);
},
selectable: "row",
toolbar: [
{ name: "create" },
{ name: "cancel" }
],
paging: false,
});
I can't understand if you want to POST empty fields as "0" or if you want to SHOW them in the grid as "0", when null or "empty".
But I guess you're talking about posting it as "0". In that case I think you have to do that before posting:
let fieldName = 'myCell';
if (data[i].dirty) {
if (!data[i].hasOwnProperty(fieldName) || // In case field is not present on data
!data[i][fieldName]) { // In case field value is null/undefined/0/false/empty string
data[i][fieldName] = 0;
}
changedModels.push(data[i].toJSON());
}
For multiple field check:
let fieldNames = ['fieldA', 'fieldB', ...],
checkFields = (item) => {
fieldNames.forEach(field => {
if (!item.hasOwnProperty(field) || // In case field is not present on data
!item[field]) { // In case field value is null/undefined/0/false/empty string
item[field] = 0;
}
});
};
Or you can do the same before data is bound to the grid with dataSource.schema.parse.

ExtJS create elements dynamically based on store items

Is it possible to create some other elements except Ext.panel.Grid using store property?
For example. Lets say that I have a panel:
Ext.create('Ext.panel.Panel', {
layout: 'vbox',
scrollable: true,
items: [
myItemsFunction()
]
}));
And from the backend I get this response:
{
"rows": [
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "de.txt",
"id": "1"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "en.txt",
"id": "2"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "it.txt",
"id": "3"
}]
}
which I load in the store:
var store_documents = Ext.create('Ext.data.Store', {
remoteSort: true,
remoteFilter: true,
proxy: {
type: 'ajax',
api: {
read: baseURL + '&SubFunc=Documents&Action=view',
},
reader: { type: 'json', rootProperty: 'rows', totalProperty: 'total' }
},
autoLoad: true
});
Now, lets say that I want to have download buttons for these three files (de.txt, en.txt, it.txt). How can I create them dynamically based on store items? I want to put it in this myItemsFunction() and show it in panel items (first block of code sample)?
Or a store is only possible to bind with Grid?
You can use ExtJs store without binding it to a grid, because Ext.data.Store has a proxy which act as ajax request when you call store.load().
So you can find this working example ExtJs Fiddle
the basic idea is to define a new panel class and to use initComponent() function to allow you to create dynamic items based on the data retrieved from the request
app.js
Ext.application({
name: 'Fiddle',
launch: function () {
var storeData = {};
let store = Ext.create('Ext.data.Store', {
storeId: 'myStoreId',
fields: ['id', 'name'],
proxy: {
type: 'ajax',
url: 'app/data.json',
reader: {
type: 'json',
rootProperty: 'rows'
}
}
});
store.load(function(){
storeData = this.getData().items;
Ext.create('Fiddle.MyPanel',{panelData:storeData});
});
}
});
app/MyPanel.js
Ext.define('Fiddle.MyPanel', {
extend: 'Ext.panel.Panel',
renderTo: Ext.getBody(),
title: 'Dynamic button creation',
width: 600,
height: 300,
initComponent: function () {
let panelItems = [];
//Creating items dynamicly
for (btn in this.panelData) {
let me = this;
panelItems.push(
Ext.create('Ext.button.Button', {
text:me.panelData[btn].data.Name
})
);
}
this.items = panelItems;
//must call this.callParent()
this.callParent();
}
})
app/data.json
{
"rows": [
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "de.txt",
"id": "1"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "en.txt",
"id": "2"
},
{
"CreateDateTime": "2015-02-09 14:05:46",
"Name": "it.txt",
"id": "3"
}]
}
Define a controller for you panel;
create an event function for afterrender;
inside it, load your store;
pass a callback parameter to your store's load function, where you iterate over loaded data creating button components;
call this.getView().add(button) to add your buttons to your panel items attribute

Is there any way to read the dojo Objectstore and convert it as JS array object

Looking for a way to read the all the rows from DOJO enhancedgrid ObjectStore as JS Array object.
OnRowClick, I need to get the all items as an array. Here is the sample code:
Layout, Id are defined in another methods. Id is first header.
IN the following code, store is dataStore.
function constructEnhancedGrid(jsObject) {
require(
["dojo/store/Memory", "dojo/data/ObjectStore",
"dojox/grid/EnhancedGrid",
"dojox/grid/enhanced/plugins/Pagination", "dojo/domReady!"
],
function(Memory, ObjectStore, EnhancedGrid, Pagination) {
jsGlobalObject = jsObject;
jsObject = JSON.parse(jsObject);
var objectStoreMemory = new Memory({
data: jsObject,
idProperty: [tableheaders[0]]
});
dataStore = new ObjectStore({
objectStore: objectStoreMemory
});
constructEnhancedGridlayout(tableheaders);
if (typeof rtGrid === "undefined") {
rtGrid = new EnhancedGrid({
store: dataStore,
structure: enhancedGridLayout,
plugins: {
pagination: {
pageSizes: ["10", "25", "50", "100"],
description: true,
sizeSwitch: false,
pageStepper: true,
gotoButton: false,
maxPageStep: 5,
position: "top",
defaultPageSize: 20
}
},
}, "rtGrid");
rtGrid.startup();
} else {
rtGrid.setStructure(enhancedGridLayout);
rtGrid.setStore(dataStore);
rtGrid.currentPage(1);
rtGrid.render(dataStore);
rtGrid.startup();
}
dojo.connect(rtGrid, "onRowClick", function(e) {
dataStore.fetch({
query: {},
onComplete: function(items) {
var resArray;
dataStore.objectStore.get().then(function(result) {
resArray = result;
});
}
});
});
});
}
Updated answer
Initially I assumed that you use JsonRest, but now I see that you use Memory object to populate your datagrid. Instance of Memory has attribute data with an array of data it contains. You can access it directly in you code.
grid.on("RowClick", function (e) {
var data = this.store.objectStore.data;
})
});

Reinitialize datatable using the new API

I've found some SO threads about reinitializing a datatable using the old API, but I think they're deprecated now.
I have an existing rendered datatable. I would like to refresh it with new settings. Using the new API, how would I do the following:
var dataTable = $('table.dataTable').DataTable();
var newDataTableSettings = {
data: { /* some data */ },
columns: { /* some columns*/ },
bFilter: false,
// etc...
};
// something like dataTable.clear().data(newDataTableSettings).draw()
My closest attempt:
dataTable.clear().draw()
dataTable.rows.add({ /* some data */ }).draw();
Use the destroy option :
$('#example').DataTable({
data: [{ test : 'test' }, { test : 'qwerty'}],
columns : [ { data : 'test', title: 'test' } ]
});
reinitialise with new data and removed search capabilities .
$("#reinit").on('click', function() {
$('#example').DataTable({
destroy: true, //<--- here
data: [{ newCol : '100010'}, { newCol : '234234'}],
columns: [ { data : 'newCol', title: 'header' } ],
searching: false
})
});
http://jsfiddle.net/3sonfsfm/
If you use an options literal you must reset it before reusing it :
var options = {
data: [{ test : 'test' }, { test : 'qwerty'}],
columns : [ { data : 'test', title: 'test' } ]
}
$("#reinit").on('click', function() {
options = {}; //<--- RESET
options.destroy = true;
options.data = [{ newCol : '100010'}, { newCol : '234234'}];
options.columns = [ { data : 'newCol', title: 'header' } ];
options.searching = false;
$('#example').DataTable(options).draw();
});
This is because the options object is enriched with different values such as aaData, aoColumns an so on, which will conflict if you specify new data and new columns.

ExtJS TaskRunner

I'm still in the learning process with EXTJS and any help would be much appreciated.
The goal for me is to load data into a grid where one cell needs to have the value incremented every minute. From my research using the TaskRunner function is the way to go but can't figure out where to put it and how to use it. My assumption is that it needs to go into the model or the controller but I'm not sure. In my simple project I'm using the MVC architecture.
Currently my gird works as expected. It reads in a file does a date conversion that produces a minute value. It's that minute value that I need to increment.
The code below is a sample TaskRunner snippit that I'm working with, right or wrong I don't know yet.
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
}),
interval: 60000 // 1-minute interval
});
task.start();
Model:
Ext.define("myApp.model.ActionItem", {
extend : "Ext.data.Model",
fields : [
{
name: 'pri',
type: 'int'
},
{
name: 'request',
type: 'int',
defaultValue: 0,
convert : function(v, model) {
return Math.round((new Date() - new Date(v)) / 60000);
}
}
]
});
Controller:
Ext.define("myApp.controller.HomeController", {
extend: "Ext.app.Controller",
id: "HomeController",
refs: [
{ ref: "ActionItemsGrid", selector: "[xtype=actionitemgrid]" },
{ ref: "DetailsPanel", selector: "[xtype=actionitemdetails]" }
],
pri: "",
models: ["ActionItem"],
stores: ["myActionStore"],
views:
[
"home.ActionItemDetailsPanel",
"home.ActionItemGrid",
"home.HomeScreen"
],
init: function () {
this.control({
"#homescreen": {
beforerender: this.loadActionItems
},
"ActionItemsGrid": {
itemclick: this.displayDetails
}
});
},
displayDetails: function (model, record) {
this.getDetailsPanel().loadRecord(record);
},
loadActionItems: function () {
var store = Ext.getStore("myActionStore");
store.load();
this.getActionItemsGrid().reconfigure(store);
}
});
View:
Ext.define("myApp.view.home.ActionItemGrid", {
extend: "Ext.grid.Panel",
xtype: "actionitemgrid",
resizable: true,
multiSelect: false,
enableDragDrop : false,
store: null,
columns:
[
{ header: "Pri", dataIndex: "pri", sortable: false, autoSizeColumn: true},
{ header: "Req", dataIndex: "request", sortable: false, autoSizeColumn: true}
],
viewConfig:
{
listeners: {
refresh: function(dataview) {
Ext.each(dataview.panel.columns, function(column) {
if (column.autoSizeColumn === true)
column.autoSize();
})
}
}
}
});
Sample JSON File:
{
"actionitems" : [
{
"pri": 1,
"request": "2014-12-30T03:52:48.516Z"
},
{
"pri": 2,
"request": "2014-12-29T05:02:48.516Z"
}
]
}
You have error in code which creates task - you should provide function to run configuration property, not result of invocation. Try this:
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: function() {
store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
})
},
interval: 60000 // 1-minute interval
});
task.start();
You can put that code in loadActionItems method.

Categories

Resources