Extjs 4.0 MVC Add components to a form based on Store - forms

I am ashamed to say I have spent most of today on this. I am trying to build a form based on the contents of an data store. I am using Ext.js and the MVC architecture. Here's what I have:
var myitems = Ext.create('Ext.data.Store', {
fields: ['name', 'prompt', 'type'],
data :
[
{"name":"name", "prompt":"Your name" , "type":"textfield"},
{"name":"addr", "prompt":"Your street address", "type":"textfield"},
{"name":"city", "prompt":"Your city" , "type":"textfield"}
]
});
function genwidget(name, prompt, type)
{
console.log("In genwidget with name=" + name + ", prompt=" + prompt + ", type=" + type + ".");
var widget = null;
if (type == "textfield")
{
// widget = Ext.create('Ext.form.field.Text',
widget = Ext.create('Ext.form.TextField',
{
xtype : 'textfield',
name : name,
fieldLabel: prompt,
labelWidth: 150,
width : 400, // includes labelWidth
allowBlank: false
});
}
else
{
// will code others later
console.log("Unrecongized type [" + type + '] in function mywidget');
}
return widget;
};
function genItems(myitems)
{
console.log("Begin genItems.");
var items = new Ext.util.MixedCollection();
var howMany = myitems.count();
console.log("There are " + howMany + " items.");
for (var i = 0; i < myitems.count(); i++)
{
var name = myitems.getAt(i).get('name');
var prompt = myitems.getAt(i).get('prompt');
var type = myitems.getAt(i).get('type');
var widget = genwidget(name, prompt, type) ;
items.add(widget);
console.log("items.toString(): " + items.toString());
}
return items;
};
Ext.define('MyApp.view.dynamicform.Form' ,{
extend: 'Ext.form.Panel',
alias : 'widget.dynamicformform',
// no store
title: 'Dynamic Form',
id: 'dynamicform.Form',
bodyPadding: 5,
autoScroll: true,
layout: 'auto',
defaults:
{
anchor: '100%'
},
dockedItems: [ ],
items: genItems(myitems),
// Reset and Submit buttons
buttons: [
{
text: 'Reset',
handler: function()
{
this.up('form').getForm().reset();
console.log('Reset not coded yet');
}
},
{
text: 'Submit',
formBind: true, //only enabled once the form is valid
disabled: true,
handler: function()
{
var form = this.up('form').getForm();
if (form.isValid())
{
form.submit({
success: function(form, action)
{
console.log('Success not coded yet');
}
});
}
}
} // end submit
], // end buttons
initComponent: function()
{
console.log("--> in dynamicform init");
this.callParent(arguments);
console.log("--> leaving dynamicform init");
}
}); // Ext.define
The error I am getting (I've had many throughout the day) is "my.items.push is not a function".
Thanks in advance for any help you can offer!

items is expected to be an array not MixedCollection. It is changed to MixedCollection later on if I remember good. So to fix your issue change:
var items = new Ext.util.MixedCollection();
// ...
items.add(widget);
to
var items = [];
// ...
items.push(widget);
Consider as well defining items of form as an empty array and then in initComponent make use of Ext.apply:
var me = this,
items = genItems(myitems);
Ext.apply(me, {
items:items
});

Related

Rendering a menu in vue 3 after ajax method

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.

Code migration from tinymce 4 to tinymce 5 - problem with action function (true / false)

I have a problem with migrating the plugin from tinymce 4 to tinymka 5. The console tells me "Uncaught (in promise) TypeError: btn.active is not a function"
I can not find an equivalent for tinymce 5. Can someone replace it?
Code below:
tinymce.PluginManager.add('phonelink', function(editor, url) {
// Add a button that opens a window
var linkText = "";
var linkTitle = "";
var link = "";
// tinymce.DOM.loadCSS(url + '/css/phonelink.css');
editor.ui.registry.addButton('phonelink2', {
text: 'asddas',
icon: 'image-options',
onSetup: updateOnSelect,
onAction: onClickPhoneButton
});
// Adds a menu item to the tools menu
editor.ui.registry.addMenuItem('phonelink', {
text: 'asddas',
icon: 'image-options',
context: 'tools',
onAction: onClickPhoneButton,
onSetup: updateOnSelect
});
function onClickPhoneButton(){
editor.windowManager.open({
title: '123213123',
body: {
type: 'panel',
items: [
{type: 'input', name: 'phone', label: 'Teléfono', value: link},
{type: 'input', name: 'showtext', label: 'Texto a mostrar', value: linkText},
{type: 'input', name: 'title', label: 'Título', value: linkTitle}
]
},
buttons: [
{
text: 'Close',
type: 'cancel',
onclick: 'close'
},
{
type: 'submit',
name: 'submitButton',
text: 'Stwórz',
primary: true
}
],
onAction: function(e) {
alert('Toggle menu item clicked');
},
onSubmit: function(e) {
var data = e.getData();
var hrefLink = '<a title="' + data .title + '" href="tel:+34' + data .phone + '">' + data .showtext + '</a>';
if(link !== ''){
editor.setContent(hrefLink);
}else{
editor.insertContent(hrefLink);
}
e.close();
}
});
}
function updateOnSelect() {
var btn = this;
const editorEventCallback = function (e) {
var node = editor.selection.getNode();
var isTelLink = node.href !== undefined && node.href.indexOf('tel:+') !== -1
btn.active(isTelLink);
if(isTelLink){
link = node.href;
link = link.replace("tel:+34", "");
linkTitle = node.title;
linkText = node.text;
}
};
editor.on('NodeChange', editorEventCallback);
return function (btn) {
editor.off('NodeChange', editorEventCallback);
}
}
});
I searched the documentation for a replacement, but found nothing.
TinyMCE 5 no longer passes the button and menu instance via this. Instead it passes an API instance as the first parameter, so you'll want to change your updateOnSelect function to something like this:
function updateOnSelect(api) {
const editorEventCallback = function (e) {
var node = editor.selection.getNode();
var isTelLink = node.href !== undefined && node.href.indexOf('tel:+') !== -1
api.setActive(isTelLink);
if(isTelLink){
link = node.href;
link = link.replace("tel:+34", "");
linkTitle = node.title;
linkText = node.text;
}
};
editor.on('NodeChange', editorEventCallback);
return function (btn) {
editor.off('NodeChange', editorEventCallback);
}
}
You'll note var btn = this has been removed and that the API to set an item as active is setActive instead of active. This can be found in the documentation here: https://www.tiny.cloud/docs/ui-components/typesoftoolbarbuttons/#togglebutton and https://www.tiny.cloud/docs/ui-components/menuitems/#togglemenuitems (see the API section in both links).
In the above, you may have noticed both reference "Toggle" items. That's another change in TinyMCE 5, as different types of buttons/menu items have a separate registration API. So you'll also need to swap to using editor.ui.registry.addToggleButton and editor.ui.registry.addToggleMenuItem. More details about that can be found here if needed: https://www.tiny.cloud/docs/migration-from-4x/#customtoolbarbuttons
Here's an example fiddle showing the changes mentioned above: https://fiddle.tiny.cloud/B5haab.
Hopefully that helps!

Fire BarcodeScannerButton after View loads

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()...

How to cancel wrapping of text in ExtJs Combobox List?

This my code:
function sim(proxy, data, delay) {
if (typeof data !== 'string') {
data = Ext.JSON.encode(data);
}
proxy.url = '/echo/json/';
proxy.actionMethods.read = "POST";
proxy.extraParams.json = data;
proxy.extraParams.delay = typeof delay == 'undefined' ? 0 : delay;
}
Ext.define('MyStore', {
extend:'Ext.data.Store',
fields:['id','name'],
proxy:{
url:'whatever',
type:'ajax',
reader:{
type:'json'
}
}
});
var myStore = new MyStore();
sim(myStore.proxy, [{id:2,name:'neil'},{id:3,name:'expert wanna-be expert wanna expert'}], 0);
Ext.define('MyForm', {
extend: 'Ext.form.Panel',
initComponent: function() {
var me = this;
Ext.applyIf(me, {
items: [
{
xtype: 'combobox',
editable:false,
store: myStore,
valueField: 'id',
displayField:'name',
}
]
});
me.callParent(arguments);
}
});
var myForm = new MyForm({renderTo:Ext.getBody()});
I don't want to increase the width of the column. I want to increase width of the combobox list respective of the text size in store inorder to cancel the wrapping of text.
Help me. Thanks in advance.
If I correctly understand your problem you can try matchFieldWidth: false config:
{
xtype: 'combobox',
editable:false,
store: myStore,
valueField: 'id',
displayField:'name',
matchFieldWidth: false
}
For additional configurations of dropdown use listConfig option.

No views are displayed in ViewRepeater with activated respnsive

I've created this view. If I activate responsive, nothing is displayed. If I deactivate responsive I see the rows. What can be the reason?
createContent : function(oController) {
var oTileTemplate = new sap.ui.commons.layout.HorizontalLayout("tileTemplate");
var oEmployeeDetailsTemplate = new sap.ui.commons.layout.VerticalLayout("employeeDetailsTemplate");
//Name
var oEmployeeNameText = new sap.ui.commons.TextView( {
text: {
parts: [
{ path: "title" },
{ path: "firstname" },
{ path: "lastname" }
]
},
});
oEmployeeDetailsTemplate.addContent(oEmployeeNameText);
//Company
var oEmployeeCompanyText = new sap.ui.commons.TextView( {
text: "{company}",
});
oEmployeeDetailsTemplate.addContent(oEmployeeCompanyText);
//Plant
var oEmployeePlantText = new sap.ui.commons.TextView( {
text: "{plant}",
});
oEmployeeDetailsTemplate.addContent(oEmployeePlantText);
//Orgunit
var oEmployeeOrgunitText = new sap.ui.commons.TextView( {
text: "{orgunit}",
});
oEmployeeDetailsTemplate.addContent(oEmployeeOrgunitText);
oTileTemplate.addContent(oEmployeeDetailsTemplate);
var oViewRepeater = new sap.suite.ui.commons.ViewRepeater("tilesViewReapeater", {
title: new sap.ui.commons.Title({text: "Employee View", level: sap.ui.commons.TitleLevel.H1}),
noData: new sap.ui.commons.TextView({text: "Sorry, no data available!"}),
showViews: false, // disable view selector
showSearchField: false,
//set view properties directly to the repeater
responsive: true,
itemMinWidth: 210,
numberOfRows: 5, // view property NumberOfTiles has legacy name here
rows: {
path: "/employees",
template: oTileTemplate
}
});
return oViewRepeater;
In HTML-Output is nothing rendered in the ViewRepeaters body ul-element.
I don't understand why the element is only rendered correctly when responsive is true? Has anybody an idea?
Thanks!
I don't see any model-binding being done, probably this is missing. (or going wrong)