UI5 Tree Binding to JSON - sapui5

I have the following JSON file.
"idocs": [
{
"Docnum": "00063463",
"Mestyp": "MATMAS",
"Status": "53",
"Sndprn": "EXTSYS1",
"Direct": "Inbound",
"Message": "Material 00002342 Created",
"messages": [{
"message": "Material 00002342 Created"
}],
"segments": [{
"segment": "E1MARAM",
"fields": [{
"fieldName": "MATNR"
}]
}]
}
I want to bind this to a tree node. I have the following code to "attempt" to do this and it is not doing anything. Not even an error.
var oTree = new sap.ui.commons.Tree("tree")
.placeAt("idViewRoot--idViewDetail--toolBar-content");
oTree.bindAggregation("nodes", tgtPath, function(
sId, oContext) {
alert("stuff");
var treePath = oContext.getPath();
var bindTextName = '';
if (treePath.indexOf("fields") !== -1) {
bindTextName = "fieldName";
} else {
bindTextName = "segment";
}
return new sap.ui.commons.TreeNode()
.bindProperty("text", bindTextName);
});
I would appreciate if someone could take a look and point me in the right direction.
Should I see an alert "stuff" appearing, because I do not even see that. Could it be an issue with the binding.
The value of tgtPath is /idocs/0/segments.
Martin

// data has to be tree structured
var oData = {
root:{
name: "root",
0: {
name: "item1",
0: {
name: "subitem1",
0: {
name: "subsubitem1"
},
1: {
name: "subsubitem2"
}
},
1: {
name: "subitem2",
0: {
name: "subsubitem3"
}
}
},
1:{
name: "item2",
0: {
name: "subitem3"
}
}
}
};
var oModel = new sap.ui.model.json.JSONModel();
// set the data to the model
oModel.setData(oData);
var oTree = new sap.ui.commons.Tree("tree");
oTree.setWidth("100%");
// set the model to the tree
oTree.setModel(oModel);
var oTreeNodeTemplate = new sap.ui.commons.TreeNode("node");
oTreeNodeTemplate.bindProperty("text", "name");
oTreeNodeTemplate.setExpanded(true);
oTree.bindAggregation("nodes", "/root", oTreeNodeTemplate);
oTree.placeAt("body");
Here is sample https://jsbin.com/rexahoquso/edit?html,js,output

Related

How to reference two different collections of same db based on object_id in mongo and fastapi

my schema for two collections.
class SectionModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
name: str = Field(max_length=50)
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"name": "",
}
}
class FaqModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
section_id:str
question:str = Field(max_length=50)
answer:str = Field(max_length=100)
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"section_id": "",
"question": "",
"answer": "",
}
}
my endpoint to create/add data
#router.post("/section",tags=["FAQ"])
def create_section(data: SectionModel = Body(...)):
try:
data = jsonable_encoder(data)
new_section = crud.create_section(data=data)
return {"success":True}
my crud method
def create_section(data):
data = db["sections"].insert_one(data)
return data
my db looks like this after adding data
db.sections.find().pretty();
[
{
_id: '63e4a4d9304637ec1b578136',
name: 'karnataka'
},
{
_id: '63e4c2056f1845a3fc2180c5',
name: 'Cricket'
}
]
db.faqs.find().pretty();
[
{
_id: '63e4cd7a1fdf5ee828bb33b9',
section_id: '63e4a4d9304637ec1b578136',
question: 'how many districts are in karnataka',
answer: '31'
},
{
_id: '63e4cd7a1fef5ee828c2b83b7',
section_id: '63e4c2056f1845a3fc2180c5',
question: 'who is called as hitman',
answer: 'Rohit sharma'
}
]
in faqs collection i am storing section_id as string and not referenced anywhere. if it is correct way then how to fetch response like,
{
"section": ["karnataka", "Cricket"],
"faq": {
"karnataka": [{
"question": "how many districts are in karnataka",
"answer": "31"
}, {
"question": "q2",
"answer": "ans2"
}],
"Cricket": [{
"question": "who is called as hitman",
"answer": "rohit sharma"
}, {
"question": "q4",
"answer": "ans4"
}]
}
}
if not this way means how to reference from the model and achieve this.
Thanks for input.

One to one with populate mongoose not working

I'm new to mongoose and mongodb.
I have two collection (cart and produk)
1 cart have 1 produk, and I get the cart and populate the product but is not show the data relations.
Here the code:
routing
router.route('/relations/:app_id')
.get(cartController.relation);
model (cartModel)
var mongoose = require('mongoose');
var cartSchema = mongoose.Schema({
app_id: {
type: String,
required: true
},
product_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Produk'
},
qty: Number
});
var collectionName = 'cart';
var Cart = module.exports = mongoose.model('Cart', cartSchema, collectionName);
module.exports.get = function (callback, limit) {
Cart.find(callback).limit(limit);
}
model (produkModel)
var mongoose = require('mongoose');
// Setup schema
var produkSchema = new Schema({
name: {
type: String,
required: true
},
stok: Number
});
// Export Cart model
var collectionName = 'produk';
var Produk = module.exports = mongoose.model('Produk', produkSchema, collectionName);
module.exports.get = function (callback, limit) {
Produk.find(callback).limit(limit);
}
controller (cartController)
Cart = require('../model/cartModel');
exports.relation = function (req, res) {
const showCart = async function() {
const carto = await Cart.find().select('app_id product_id qty').populate("produk");
return carto;
};
showCart()
.then(cs => {
return apiResponse.successResponseWithData(res, "Operation success", cs);
})
.catch(err => console.log(err));
};
// Result
{
"status": 1,
"message": "Operation success",
"data": [
{
"_id": "60af72022d57d542a41ffa5a",
"app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
"qty": 1,
"product_id": "60112f3a25e6ba2369424ea3"
},
{
"_id": "60b020536ccea245b410fb38",
"app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
"product_id": "603f5aff9437e12fe71e6d41",
"qty": 1
}
]
}
expecting result
{
"status": 1,
"message": "Operation success",
"data": [
{
"_id": "60af72022d57d542a41ffa5a",
"app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
"qty": 1,
"product_id": {
"_id": "60112f3a25e6ba2369424ea3",
"name": "snack"
}
},
{
"_id": "60b020536ccea245b410fb38",
"app_id": "CvR4dTTjC7qgr7gA2yoUnIJnjRXaYokD6uc2pkrp",
"product_id": {
"_id": "603f5aff9437e12fe71e6d41",
"name": "snack"
}
"qty": 1
}
]
}
what I miss ???
Thanks for your help
You need to pass the path to populate or an object specifying parameters to .populate(). So in this case, Your code should be:
const carto = await Cart.find().select('app_id product_id qty').populate("product_id");

All appointments have a different row (sap.m.PlanningCalendar)

I am trying to port my old application with "sap.me.OverlapCalendar" to the new "sap.m.PlanningCalendar", I want to show appointments just for one person. I found a difference in the way the appointments display.
The template I use is:
var oTemplateRow = new sap.m.PlanningCalendarRow("RowTemplate", {
appointments:[
new sap.ui.unified.CalendarAppointment({
startDate: {
path: 'CalendarModel>DateFrom',
formatter: util.Formatter.toStartDate
},
endDate: {
path: 'CalendarModel>DateTo',
formatter: util.Formatter.toEndDate
},
title: "{CalendarModel>CardName} - {CalendarModel>ProjectName}",
text: "Gewerkte uren: {CalendarModel>WorkedHours}",
type: "Type04",
tentative: false,
key: "{CalendarModel>ReportID}"
})]
});
Which is bound to the Calendar control with:
bindAggregation("rows", "CalendarModel>/Items/", oTemplateRow);
The data is showing in the calendar but the way it shows is different.
Old calendar: http://imgur.com/3glZRtT
New calendar: http://imgur.com/snnsWVE
What should I do to get the same output?
You have to change the model: for example, at the root of the model you create an array corresponding to rows of the calendar, and each row should contain an array of appointments.
A sample json file can look like this:
{
"items": [{
"title": "Item1",
"appointments": [{
"text": "appointment1",
"start": "2017-02-17T09:30:00",
"end": "2017-02-17T13:00:00"
}, {
"text": "appointment2",
"start": "2017-02-17T09:45:00",
"end": "2017-02-17T13:10:00"
}]
}, {
"title": "Item2",
"appointments": [{
"text": "appointment3",
"start": "2017-02-17T10:30:00",
"end": "2017-02-17T14:00:00"
}, {
"text": "appointment4",
"start": "2017-02-17T10:45:00",
"end": "2017-02-17T14:10:00"
}]
}]
}
"items" is an array of calendar rows, and each item contains array of appointments. The binding of the control should be more complex. I used such a file a base for JSON model and the controller code looks like this:
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("QuickStartApplication.controller.View1", {
onInit: function() {
var oCale = this.getView().byId("PC1");
var oModel = this.getOwnerComponent().getModel("CalendarModel");
this.getView().setModel(oModel, "CalendarModel");
var oTemplateRow = new sap.m.PlanningCalendarRow("RowTemplate", { title: "{CalendarModel>title}" });
oTemplateRow.bindAggregation("appointments", {
path: "CalendarModel>appointments",
template: new sap.ui.unified.CalendarAppointment({
title: "{CalendarModel>text}",
startDate: {
path: "CalendarModel>start",
formatter: this.toDate
},
endDate: {
path: "CalendarModel>end",
formatter: this.toDate
}
}),
templateShareable: true
});
oCale.bindAggregation("rows", {
path: "CalendarModel>/items",
template: oTemplateRow,
templateShareable: true
});
},
toDate: function(sValue) {
if (sValue) {
return new Date(sValue); //
}
}
});
});
Note that first you create a row template and then bind its "appointments" aggregation to the "appointments" property of "CalendarModel" model with template for CalendarAppointment creation. Then you create a binding for calendar rows referring to the row template.

How to traverse JSON model?

Image
Controller.js
item: function(evt) {
var list = sap.ui.getCore().byId('appListId');
var sItem = list.getSelectedItem();
var oBindingContext = sItem.getBindingContext('products');
var sPath = oBindingContext.sPath;
console.log(sPath); // get path /collection/0/App/0
var context = sap.ui.getCore().byId("appListId").getModel('products')
.getContext(sPath);
var start = sPath.lastIndexOf("/") + 1;
var appIndex = sPath.substring(start, sPath.length);
this.router.navTo("selectedAppRecord", {
catIndex : this.subCatIndex,
appIndex : appIndex
});
}
Path of JSON Array :
get this path /collection/0/App/0
I have an JSON array :
{
"collection": [{
"model": "08 Report Fraud",
"App": [{
"App": "COUNCIL001",
"description": "Benefit Fraud",
"module": "08 Report Fraud",
"iConClass": "icon-devil",
"UserSpecific": "Yes"
}]
}]
}
finally my goal is how to get this UserSpecific key in control side.
You can use the getProperty function of the BindingContext to get relative properties.
var oItem = sap.ui.getCore().byId('appListId').getSelectedItem();
oItem.getBindingContext('products').getProperty('UserSpecific');
In your handler function I would recommend to get the current item from the event:
oEvent.getSource() || oEvent.getSource().getSelectedItem()
Depending on the type of event (ListItem#select or List#selectionChange).

Kendo DataSource: How to define "Computed" Properties for data read from remote odata source

Situation:
kendo DataSource
var ordersDataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: "http://localhost/odata.svc/Orders?$expand=OrderDetails"
}
},
schema: {
type: "json",
data: function(response){
return response.value;
}
total: function(response){
return response['odata.count'];
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
})
the json data read from the odata source is like:
{
odata.metadata: "xxxx",
odata.count: "5",
value: [
{
OrderId: 1,
OrderedDate: "2013-02-20",
OrderInfoA: "Info A",
OrderInfoB: "Info B"
OrderDetails: [
{
OrderDetailId: 6,
OrderDetailInfoC: "Info C",
OrderDetailInfoD: "Info D"
},
{
//Another OrderDetail's data
}
]
},
{
// Another Order's data
}
]
}
Question 1:
1.If I wanna define a "computed" property: OrderedDateRelative, which should be the number of days between Today(2013-02-25) and the Day the Order was Created(2013-02-20), Like: "5 days ago", HOW can i achieve this in the client side?
Answer to Question1: http://jsbin.com/ojomul/7/edit
Question 2 --UPDATE--
2.Every Order has its Nested Property OrderDetails, so is it possible to define a Calculated Field for the Nested OrderDetails Property? Like: OrderDetailInfoCAndD for each OrderDetail, and the value should be something like: OrderDetailInfoC + OrderDetailInfoD, which is "Info C Info D"?
Thanks,
dean
You can create a calculated field by specifying the model of the data source:
dataSource = new kendo.data.DataSource({
data: [
{ first: "John", last: "Doe" },
{ first: "Jane", last: "Doe" }
],
schema: {
model: {
// Calculated field
fullName: function() {
return this.get("first") + " " + this.get("last");
}
}
}
});
Here is a live demo: http://jsbin.com/ojomul/1/edit
Here is a way to use calculated field in Kendo Grid.
var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
}
},
pageSize: 20,
schema: {
model: {
total: function (item) {
return this.UnitPrice * this.UnitsInStock;
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
sortable: true,
filterable: true,
toolbar: ["create"],
columns: [
{ field: "UnitPrice", title: "Unit Price"},
{ field: "UnitsInStock", title: "Units In Stock", width: "120px" },
{ field: "total()", title: "Total" }]
});
Below an example to use it in a grid. It can then also sort the column.
$("#grid").kendoGrid({
dataSource: {
data: [
{ first: "John", last: "Doe" },
{ first: "Jane", last: "Doe" }
],
schema: {
model: {
// Calculated field
fullName: function() {
return this.first + " " + this.last;
},
fields: {
first: { type: "string" },
last: { type: "string" }
}
}
}
},
columns: [
{
// Trigger function of the Calculated field
field: "fullName()",
title: "Fullname"
},
{
field: "first",
title: "firstname"
}
]
});