Assume I have a SAPUI5 application like this sample application.
As it can be seen in the code of this application, the views are somehow split into several blocks and attached to main view like this:
<ObjectPageSubSection title="Payment information">
<blocks>
<personal:PersonalBlockPart1 id="part1"/>
</blocks>
<moreBlocks>
<personal:PersonalBlockPart2 id="part2"/>
</moreBlocks>
</ObjectPageSubSection>
And the PersonalBlockPart1 has been split into two files like this:
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:core="sap.ui.core" xmlns:forms="sap.ui.layout.form" xmlns="sap.m">
<forms:SimpleForm editable="false" layout="ColumnLayout">
<core:Title text="Main Payment Method"/>
<Label text="Bank Transfer"/>
<Text text="Sparkasse Heimfeld, Germany"/>
</forms:SimpleForm>
</mvc:View>
sap.ui.define(['sap/uxap/BlockBase'], function (BlockBase) {
"use strict";
var BlockJobInfoPart1 = BlockBase.extend("sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1", {
metadata: {
views: {
Collapsed: {
viewName: "sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1",
type: "XML"
},
Expanded: {
viewName: "sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1",
type: "XML"
}
}
}
});
return BlockJobInfoPart1;
});
If I want to set fieldGroupIds a direct way is to do it in xml fragment of the code! for example:
<Text text="Sparkasse Heimfeld, Germany" fieldGroupIds="XYZ1"/>
My question is how can I do it in the parent view, something like this:
<blocks>
<personal:PersonalBlockPart1 id="part1" fieldGroupIds="XYZ1"/>
</blocks>
<moreBlocks>
<personal:PersonalBlockPart2 id="part2" fieldGroupIds="XYZ2"/>
</moreBlocks>
I tried it, and obviously it does not apply to children controls. However, I think there could be a solution that read this property from main XML view and apply it in the JS file on all the enclosing controls, something like this:
sap.ui.define(['sap/uxap/BlockBase'], function (BlockBase) {
"use strict";
var BlockJobInfoPart1 = BlockBase.extend("sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1", {
metadata: {
views: {
Collapsed: {
viewName: "sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1",
type: "XML"
},
Expanded: {
viewName: "sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1",
type: "XML"
}
}
},
onViewInit: function(){
// pseudocode
var sFieldGroupIds = this.getFieldGroupIds();
var aControls = this.getAllFeidls();
iterate over aControls and set the sFieldGroupId
}
});
return BlockJobInfoPart1;
});
I must use the onBeforeRendering function:
sap.ui.define(['sap/uxap/BlockBase'], function (BlockBase) {
"use strict";
var setFieldGroupIdsRecursively = function (oControl, sFieldGroupIds) {
var aPossibleAggregations = ["items", "content", "form", "formContainers", "formElements", "fields", "cells"];
if (oControl instanceof sap.m.InputBase || oControl instanceof sap.ui.comp.smartfield.SmartField) {
oControl.setFieldGroupIds(sFieldGroupIds);
return;
}
for (var i = 0; i < aPossibleAggregations.length; i += 1) {
var aControlAggregation = oControl.getAggregation(aPossibleAggregations[i]);
if (aControlAggregation) {
// generally, aggregations are of type Array
if (aControlAggregation instanceof Array) {
for (var j = 0; j < aControlAggregation.length; j += 1) {
setFieldGroupIdsRecursively(aControlAggregation[j], sFieldGroupIds);
}
}
else { // ...however, with sap.ui.layout.form.Form, it is a single object *sigh*
setFieldGroupIdsRecursively(aControlAggregation, sFieldGroupIds);
}
}
}
};
var BlockJobInfoPart1 = BlockBase.extend("sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1", {
metadata: {
views: {
Collapsed: {
viewName: "sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1",
type: "XML"
},
Expanded: {
viewName: "sap.uxap.sample.SharedBlocks.employment.BlockJobInfoPart1",
type: "XML"
}
}
},
onBeforeRendering: function () {
var aFieldGroupIds = this.getFieldGroupIds(),
sFieldGroupIds = "";
if (aFieldGroupIds.length > 0) {
sFieldGroupIds = aFieldGroupIds.join();
var oView = sap.ui.getCore().byId(this.getSelectedView());
if (oView) {
var aContent = oView.getContent();
for (var j = 0; j < aContent.length; j++) {
setFieldGroupIdsRecursively(aContent[j], sFieldGroupIds);
}
}
}
}
});
return BlockJobInfoPart1;
});
Related
I've gotten this menu to work without filtering it, but now I'm doing an ajax request to filter out menu items the user isn't supposed to see, and I'm having some trouble to figure out how to set the resulting menu data, the line that is not working is commented below:
<script>
import { ref } from 'vue';
import axios from 'axios';
var currentSelected = 'device_access';
var menuData = [
{
text: 'Device Access',
id: 'device_access',
children: [
{
text: 'Interactive',
link: '/connection_center'
},{
text: 'Reservation',
link: '/reserve_probe'
}, {
text: 'Reservation Vue',
link: '/reservation.html'
}
]
}, {
text: 'Automation',
id: 'automation',
show: ['is_mxadmin', 'can_schedule_scripts'],
children: [
{
text: 'Builder',
link: '/builder',
},{
text: 'Execution Results',
link: '/test_suite_execution_results'
},
]
}
];
function hasMatch(props, list) {
var match = false;
for (var i=0; i < list.length && !match; i++) {
match = props[list[i]];
}
return match;
}
export default {
name: 'Header',
setup() {
const cursorPosition = ref('0px');
const cursorWidth = ref('0px');
const cursorVisible = ref('visible');
//the menu is zero length until I get the data:
const menu = ref([]);
return {
menu,
cursorPosition,
cursorWidth,
cursorVisible
}
},
created() {
let that = this;
axios.get('navigation_props')
.then(function(res) {
var data = res.data;
var result = [];
menuData.forEach(function(item) {
if (!item.show || hasMatch(data, item.show)) {
var children = [];
item.children.forEach(function (child) {
if (!child.show || hasMatch(data, child.show)) {
children.push({ text: child.text, link: child.link });
}
});
if (children.length > 0) {
result.push({ text: item.text,
children: children, lengthClass: "length_" + children.length });
}
}
});
//continues after comment
this is probably the only thing wrong, I've run this in the debugger and I'm getting the
correct data:
that.$refs.menu = result;
since the menu is not being rebuilt, then this fails:
//this.restoreCursor();
})
.catch(error => {
console.log(error)
// Manage errors if found any
});
},
this.$refs is for template refs, which are not the same as the refs from setup().
And the data fetching in created() should probably be moved to onMounted() in setup(), where the axios.get() callback sets menu.value with the results:
import { onMounted, ref } from 'vue'
export default {
setup() {
const menu = ref([])
onMounted(() => {
axios.get(/*...*/).then(res => {
const results = /* massage res.data */
menu.value = results
})
})
return {
menu
}
}
}
I finally figured out the problem.
This code above will probably work with:
that.menu = result;
You don't need: that.$refs.menu
You can't do it in setup because for some reason "that" is not yet defined.
In my working code I added a new method:
methods: {
setMenuData: function() {
this.menu = filterMenu();
},
}
And "this" is properly defined inside them.
I am getting data from oModel, and it {msgData} object
var Buttons = [{text:"apple"},{text:"banana"}];
var sQuery = "some text...";
oModel.oData.msgData.push({
Type : "Information",
buttons:Buttons,
customIcon:"media/chat/b_small.png",
Text: sQuery
});
oModel.refresh();
(in xml file, you can see the code below)
XML:
<wt:MessageStrip
text="{msgData>Text}"
type="{msgData>Type}"
>
// ***** NEED TO ADD THESE LINES ****
<List items="{msgData>buttons}" class="fixFlexFixedSize BtnBox">
<Button press="BtnClick" text="{msgData>text}" class="sapUiTinyMarginEnd"/>
</List>
</wt:MessageStrip>
How can I add Button list to a control?
(Button list is in {msgData} object)
MessageStrip.js
sap.ui.define(["sap/m/MessageStrip"],
function (MessageStrip) {
"use strict";
return MessageStrip.extend("com.sap.it.cs.itsdpphome.controller
.fragments.MessageStrip", {
metadata: {
properties: {
},
aggregations: {
},
events: {
}
},
init: function () {
},
renderer:{}
});
});
First of all, you cannot add Button to a List. You have to use sap.m.CustomListItem to put a Button as content.
Let's get to the part about how to meet your current requirement for custom control.
you have define a aggregations for your MessageStrip to put your List
sap.ui.define(["sap/m/MessageStrip"],
function (MessageStrip) {
"use strict";
return MessageStrip.extend("com.sap.it.cs.itsdpphome.controller.fragments.MessageStrip", {
metadata: {
properties: {
},
aggregations: {
list: { type: "sap.m.ListBase", multiple: false }
},
events: {
}
},
init: function () {
MessageStrip.prototype.init.call(this);
},
renderer: {}
});
});
Then you define your own Renderer which extends sap/m/MessageStripRenderer for your MessageStrip. In order to render your list inside a MessageStrip, you have to copy some code from sap/m/MessageStripRenderer.
sap.ui.define(['sap/ui/core/Renderer', 'sap/m/MessageStripRenderer'],
function (Renderer, MessageStripRenderer) {
"use strict";
var MessageStripRenderer = Renderer.extend(MessageStripRenderer);
MessageStripRenderer.render = function (oRm, oControl) {
this.startMessageStrip(oRm, oControl);
this.renderAriaTypeText(oRm, oControl);
if (oControl.getShowIcon()) {
this.renderIcon(oRm, oControl);
}
this.renderTextAndLink(oRm, oControl);
//Render your list aggregation
oRm.renderControl(oControl.getAggregation("list"));
if (oControl.getShowCloseButton()) {
this.renderCloseButton(oRm);
}
this.endMessageStrip(oRm);
}
return MessageStripRenderer;
}, true);
I tried the below view XML and it renders like the following screenshot.
<wt:MessageStrip text="DUMMY">
<wt:list>
<List>
<items>
<CustomListItem><Button text="1" /></CustomListItem>
<CustomListItem><Button text="2" /></CustomListItem>
<CustomListItem><Button text="3" /></CustomListItem>
</items>
</List>
</wt:list>
</wt:MessageStrip>
Hope it helps. Thank you!
I have implemented a scanner button on my Fiori/UI5 application. I used sap.ndc.BarcodeScannerButton and created that button on the controller (I cannot seem to create the button on my view.xml).
Anyway, I need to fire this button after the view loads. I have a master-detail application. The scanner button is on the master view ofcourse.
First thing I did was call the button itself. But my first problem is that the button does not accept an id as a parameter. It tells me that app cannot accept duplicate id. So what I did was just look for the button id. I was able to locate it (e.g. _button9) but whenever I call it via sap.ui.getCore.byId() there are times that it returns "undefined." That's why I cannot call firePress();
Another problem I have is where to put this firePress() method. I tried to put it on method onAfterRendering() assuming that again due to the undefined button I cannot call the method firePress(). I have tried putting it on other methods like after the data has been successfully called by using method attachRequestCompleted. No luck.
Below is the code
/*
* Copyright (C) 2009-2014 SAP SE or an SAP affiliate company. All rights reserved
*/
jQuery.sap.require("sap.ca.scfld.md.controller.ScfldMasterController");
jQuery.sap.require("ui.s2p.srm.sc.create.util.Formatter");
jQuery.sap.require("sap.ndc.BarcodeScannerButton");
var counter = 0;
sap.ui.controller("ui.s2p.srm.sc.create.SRM_SC_CREExtension.view.S2Custom", {
onInit: function() {
sap.ca.scfld.md.controller.ScfldMasterController.prototype.onInit.call(this);
this.oBundle = this.oApplicationFacade.getResourceBundle();
this.isRoot = true;
this.oRouter.attachRouteMatched(function(e) {
if (e.getParameter("name") === "master" && !this.isRoot && Object.keys(e.getParameter("arguments")).length === 0) {
var d = sap.ui.core.routing.History.getInstance().getDirection("shoppingCartCheckout/" + this.tempCartId);
if (d === "Unknown") {
this.isRoot = true;
this._oControlStore.oMasterSearchField.clear()
} else {
if (this.getList() !== null) {
var i = this.getList().getSelectedItem();
if (i !== null) {
//alert("setListGo");
this.setListItem(i);
}
}
}
}
this.isRoot = (this.isRoot) ? false : this.isRoot;
}, this);
// alert(sap.ui.getCore().byId("productScanButton"));
this.onBarcodeScanning();
this.setEmptyCart(true);
this.showAllProducts(); //added by salduam to show all products
},
backToList: function() {
//alert("back");
},
getDefaultUserSettings: function(r) {
var o = function(D, R) {
this.tempCartId = D.results[0].TEMP_CART_ID;
if (!jQuery.device.is.phone) {
if (r) {
this.oRouter.navTo("noData", {
viewTitle: "DETAIL_TITLE",
languageKey: "NO_ITEMS_AVAILABLE"
}, true)
} else {
this.navToEmptyView()
}
}
};
var d = this.oApplicationFacade.getODataModel("getdefusrset");
d.read("DefaultUserSettings?ts=" + Date.now(), null, null, true, jQuery.proxy(o, this), jQuery.proxy(this.onRequestFailed, this))
},
applySearchPatternToListItem: function(i, f) {
if (f.substring(0, 1) === "#") {
var t = f.substr(1);
var d = i.getBindingContext().getProperty("Name").toLowerCase();
return d.indexOf(t) === 0
} else {
return sap.ca.scfld.md.controller.ScfldMasterController.prototype.applySearchPatternToListItem.call(null, i, f)
}
},
getHeaderFooterOptions: function() {
var o = {
sI18NMasterTitle: "MASTER_TITLE",
buttonList: []
};
return o
},
isBackendSearch: function() {
return true
},
//call startReadListData with parameter wildcard
showAllProducts: function(e) {
var startSearchText = "*";
this.startReadListData(startSearchText);
//alert("called");
},
applyBackendSearchPattern: function(f, b) {
//added by salduam
//if search field is blank, automatically call showAllProducts
if (f == "") {
this.showAllProducts()
};
if (f != "" && f != null) {
this.startReadListData(f)
} else {
this.setEmptyCart(false)
}
},
startReadListData: function(f) {
var o = function(D, r) {
var m = new sap.ui.model.json.JSONModel(D.results);
this.getView().setModel(m);
this.getList().destroyItems();
this.getList().bindAggregation("items", {
path: "/",
template: this.oTemplate.clone(),
filter: [],
sorter: null
});
this.registerMasterListBind(this.getList());
};
var e = encodeURIComponent(f);
//console.log("EEEE-----"+ e);
var d = this.oApplicationFacade.getODataModel();
//console.log(d);
d.read("CATALOG_ITEM?$filter=startswith(description,'" + e + "')&$top=20", null, null, true, jQuery.proxy(o, this), jQuery.proxy(this.onRequestFailed,
this));
},
setListItem: function(i) {
// alert("onClick");
var b = i.getBindingContext();
var m = b.oModel.oData[parseInt(b.sPath.split('/')[1])];
this.oRouter.navTo("detail", {
tempCartId: this.tempCartId,
contextPath: b.getPath().substr(1)
}, true);
var c = sap.ui.core.Component.getOwnerIdFor(this.oView);
var C = sap.ui.component(c);
C.oEventBus.publish("ui.s2p.srm.sc.create", "refreshDetail", {
data: m
});
},
setEmptyCart: function(r) {
var e = new sap.ui.model.json.JSONModel({
results: []
});
this.oRouter.navTo("noData", {
viewTitle: "DETAIL_TITLE",
languageKey: "NO_ITEMS_AVAILABLE"
}, true);
this.getView().setModel(e);
this.oTemplate = new sap.m.ObjectListItem({
type: "{device>/listItemType}",
title: "{matnr}",
press: jQuery.proxy(this._handleItemPress, this),
number: "{parts:[{path:'itm_price'},{path:'itm_currency'}],formatter:'ui.s2p.srm.sc.create.util.Formatter.formatPrice'}",
numberUnit: "{itm_currency}",
attributes: [new sap.m.ObjectAttribute({
text: "{description}"
})],
});
this.getList().bindAggregation("items", {
path: "/results",
template: this.oTemplate,
filter: [],
sorter: null,
});
this.registerMasterListBind(this.getList());
this.getDefaultUserSettings(r)
},
onRequestFailed: function(e) {
jQuery.sap.require("sap.ca.ui.message.message");
sap.ca.ui.message.showMessageBox({
type: sap.ca.ui.message.Type.ERROR,
message: e.message,
details: e.response.body
})
},
onExit: function() {},
onBarcodeScanning: function(oEvent) {
var productScanButton = new sap.ndc.BarcodeScannerButton({
provideFallback: "{/btnFallback}",
width: "100%",
scanSuccess: function(oEvent) {
var barcodeID = oEvent.getParameter("text");
sap.m.MessageToast.show(barcodeID);
var searchField = sap.ui.getCore().byId("__field3");
searchField.setValue(barcodeID);
searchField.fireSearch();
}
});
this.getView().byId("barCodeVBox").addItem(productScanButton);
},
onAfterRendering: function(oEvent) {},
onBeforeRendering: function() {}
});
For placing the fire() method. Are you trying to display a pop-up barcode reader? something similar to the pop-up of the app "SD_SO_CRE" (where customer selection dialog is load before master view).
they do not solve the task with fire()...
I would like to use tinyMCE with a custom Slick Editor outside of the table, or inside a dialog. It's just to enable rich text editing.
Can I use this external plugin for a custom Slick Editor? I have not seen any example of usages like this.
Is there any potential problems using this two plugins at the same time (injecting conflicting HTML for example or preventing some firing events)?
Use a jquery alias "jQuery_new" with a compatible version
Register the new editor "TinyMCEEditor" & Add it into slick.editors.js
Use it like this {id: "column2", name: "Year", field: "year", editor: Slick.Editors.TinyMCE}
jQuery_new.extend(true, window, {
"Slick": {
"Editors": {
(..)
"TinyMCE": TinyMCEEditor
}
}});
function TinyMCEEditor(args) {
var $input, $wrapper;
var defaultValue;
var scope = this;
this.guid = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4();
},
this.init = function () {
var $container = jQuery_new(".container");
var textAreaIdString = 'rich-editor-'+guid();
$wrapper = jQuery_new("<DIV ID='rds-wrapper'/>").appendTo($container);
$input = jQuery_new("<TEXTAREA id=" + textAreaIdString + "/>");
$input.appendTo($wrapper);
jQuery_new("#" +textAreaIdString).val( args.item[args.column.field] );
var _this = this;
tinymce.init({
selector: "#"+textAreaIdString,
forced_root_block : "",
plugins : "save image imagetools",
toolbar: 'undo redo | styleselect | bold italic | link image | save',
save_onsavecallback: function() {
jQuery_new("#" +textAreaIdString).val( this.getContent() );
_this.save();
}
});
$input.bind("keydown", this.handleKeyDown);
scope.position(args.position);
$input.focus().select();
};
this.handleKeyDown = function (e) {
if (e.which == jQuery_new.ui.keyCode.ENTER && e.ctrlKey) {
scope.save();
} else if (e.which == jQuery_new.ui.keyCode.ESCAPE) {
e.preventDefault();
scope.cancel();
} else if (e.which == jQuery_new.ui.keyCode.TAB && e.shiftKey) {
e.preventDefault();
args.grid.navigatePrev();
} else if (e.which == jQuery_new.ui.keyCode.TAB) {
e.preventDefault();
args.grid.navigateNext();
}
};
this.save = function () {
args.commitChanges();
};
this.cancel = function () {
$input.val(defaultValue);
args.cancelChanges();
};
this.hide = function () {
$wrapper.hide();
};
this.show = function () {
$wrapper.show();
};
this.position = function (position) {
};
this.destroy = function () {
$wrapper.remove();
};
this.focus = function () {
$input.focus();
};
this.loadValue = function (item) {
$input.val(defaultValue = item[args.column.field]);
$input.select();
};
this.serializeValue = function () {
return $input.val();
};
this.applyValue = function (item, state) {
item[args.column.field] = state;
};
this.isValueChanged = function () {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
this.init();
}
I am making DOM object through javascript and i want it to render it through angularjs but it display like [object HTMLDivElement]
but in browser console its
but it renders like
.directive('attachmentify', [
function() {
return {
restrict: 'A',
scope: {
item: "#filename"
},
template: "<div ng-bind-html='content'></div>",
compile: function(iElement, iAttrs) {
return function($scope, element, attr) {
var file = $scope.item;
// console.log
// $scope.file =file;
}
},
controller: function($scope) {
var img = ['jpg', 'jpeg', 'png'];
var c = 0;
img.forEach(function(element, index) {
if ($scope.item.endsWith(element)) c++;
});
if (c) {
var div = document.createElement('div');
div.setAttribute('name', 'samundra')
div.innerHTML = "ram"
} else {
var div = document.createElement('div');
div.setAttribute('name', 'ramundra')
div.innerHTML = "sam"
}
$scope.content = div;
console.log(div);
}
}
}
])
In your controller instead of assign DOM element instance, You can set $scope.content to html
$scope.content="<div name='ramundra'>ram></div>";