dojo.data.ItemFileReadStore: Invalid item argument. while reloading data - dojox.grid.datagrid

I am facing a strange problem here. I have a Select box displaying Department field value. Onchange of the department option, I have to populate the grid. When the page loads first time, the onChange event works fine and the data gets loaded perfectly in the grid. When I change the Department in the Select box, I get error in firebug "dojo.data.ItemFileReadStore: Invalid item argument".
I checked the JSON returned from server and it is exactly same as the JSON loaded earlier. Here are the code snippet of my code
HTML
<div id="costCenter" data-dojo-type="dijit/form/Select" data-dojo-attach-point="costCenter" data-dojo-attach-event="onChange:loadStacks"></div>
JS
loadStacks: function() {
var requestParams = {};
requestParams.Action = "getStacks";
requestParams.callType = "ajaxCall";
requestParams.deptID = deptID;
var docData = null;
request.invokePluginService("MyPlugin", "UtilityService",
{
requestParams: requestParams,
requestCompleteCallback: lang.hitch(this, function(response) { // success
docData= response.Data;
var dataStore = new dojo.data.ItemFileReadStore({data: docData});
grid = dijit.byId("docGrid");
grid.attr('structure', docStructure);
grid.attr('store', dataStore);
grid.render();
})
}
);
}
JSON data returned:
docData : {"items":[{"docName":"test3","id":135,"order":1},{"docName":"Ashish","id":4085,"order":21},{"docName":"fsdfsadf","id":4088,"order":23}],"identifier":"docName"}
Any idea about it?

Solved it myself. Added below lines before setting new store to the grid.
if (null != grid.store)
{
grid.store.close();
grid.store.fetch({query: {docName: "*"}});
grid._refresh();
}
And set clearOnClose: true while setting new store.

Related

Wagtail - how to get tags to work with `telepath` (tags in streamfield)?

I can use tags in regular page fields without any issue. When using tags within blocks (within a streamfield), the UI works and the tags are saved BUT the current page tags do not show up when loading the page in the admin. That's because the current value is not in the template anymore, it's in a JSON loaded via telepath.
I can confirm that the tags are saved and present in the data passed to initBlockWidget in the page source but these are ignored. Also, if I used a regular text field instead of the tag-widget, I can see the saved-values in the admin.
This is the code I have (which used to be enough before the refactor with telepath).
from wagtail.admin.widgets import AdminTagWidget
class TagBlock(TextBlock):
#cached_property
def field(self):
field_kwargs = {"widget": AdminTagWidget()}
field_kwargs.update(self.field_options)
return forms.CharField(**field_kwargs)
I think the following link is what I need to complete somehow to get it to work: https://docs.wagtail.io/en/stable/reference/streamfield/widget_api.html#form-widget-client-side-api
I've tried with this:
class AdminTagWidgetAdapter(WidgetAdapter):
class Media:
js = [
"wagtailadmin/js/vendor/tag-it.js",
"js/admin/admin-tag-widget-adapter.js",
]
register(AdminTagWidgetAdapter(), AdminTagWidget)
And under js/admin/admin-tag-widget-adapter.js:
console.log("adapter"); // this shows up in the console
class BoundWidget { // copied from wagtail source code
constructor(element, name, idForLabel, initialState) {
var selector = ':input[name="' + name + '"]';
this.input = element.find(selector).addBack(selector); // find, including element itself
this.idForLabel = idForLabel;
this.setState(initialState);
}
getValue() {
return this.input.val();
}
getState() {
return this.input.val();
}
setState(state) {
this.input.val(state);
}
getTextLabel(opts) {
const val = this.getValue();
if (typeof val !== 'string') return null;
const maxLength = opts && opts.maxLength;
if (maxLength && val.length > maxLength) {
return val.substring(0, maxLength - 1) + '…';
}
return val;
}
focus() {
this.input.focus();
}
}
// my code here:
class AdminTagWidget {
constructor(html, idPattern) {
this.html = html;
this.idPattern = idPattern;
}
boundWidgetClass = BoundWidget;
render(placeholder, name, id, initialState) {
console.log("RENDER", placeholder, name, id, initialState); // this does not show
var html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id);
var idForLabel = this.idPattern.replace(/__ID__/g, id);
var dom = $(html);
$(placeholder).replaceWith(dom);
// eslint-disable-next-line new-cap
return new this.boundWidgetClass(dom, name, idForLabel, initialState);
}
}
console.log("here") // does show in the console
// variants I've tried:
//window.telepath.register('wagtail.admin.widgets.tags.AdminTagWidget', AdminTagWidget);
//window.telepath.register('wagtail.widgets.AdminTagWidget', AdminTagWidget);
window.telepath.register('path.where.its.used.AdminTagWidget', AdminTagWidget)
The log from my custom render method does not show. It seems that I'm not calling the right path within window.telepath.register but I don't know how what the string is supposed to be...
I'm not even sure if this is the right way forward.
Notes:
it works in regular field, the question is about tags in blocks
I'm using Wagtail version 2.13.2 but I've also tried with 2.15 without any difference.
In the console, I can log window.telepath and see my custom widget. It's just not "applied" to anything
Your WidgetAdapter class needs a js_constructor attribute:
class AdminTagWidgetAdapter(WidgetAdapter):
js_constructor = 'myapp.widgets.AdminTagWidget'
class Media:
js = [
"wagtailadmin/js/vendor/tag-it.js",
"js/admin/admin-tag-widget-adapter.js",
]
Any string value will work here - it just needs to uniquely identify the class, so it's recommended to use a dotted module-like path to avoid colliding with others. This then matches the string you pass to window.telepath.register on the Javascript side:
window.telepath.register('myapp.widgets.AdminTagWidget', AdminTagWidget)

How to create a local empty JSON Model from OData metadata

Is there a way to create a local empty JSON file (with all entities and properties filled in) from the metadata of the oData service? I need this for the create scenario, where I can bind the properties to the view controls. I tried the following code, but did not work. Will appreciate your suggestions.
this.getOwnerComponent().getModel().getMetaModel().getODataEntitySet("EntitySetName");
Error:
Uncaught TypeError: Cannot read property 'getObject' of null
at constructor.h.getODataEntityContainer (ODataMetaModel-dbg.js:692)
at constructor.h.getODataEntitySet (ODataMetaModel-dbg.js:731)
at eval (eval at _prepareCreatePage (ObjectPage.controller.js:74), <anonymous>:1:48)
at f._prepareCreatePage (ObjectPage.controller.js:74)
at f._onObjectPatternMatched (ObjectPage.controller.js:40)
at constructor.b.fireEvent (EventProvider-dbg.js:228)
at constructor.<anonymous>
SAP does very similar stuff in their sample pages: https://sapui5.hana.ondemand.com/#/entity/sap.ui.table.Table/sample/sap.ui.table.sample.OData2/code
Your first part is more or less correct, this is a function to store the meta model in a seperate JSONModel:
function () {
const that = this;
const oModel = this.getOwnerComponent().getModel();
const oMetaModel = oModel.getMetaModel();
oMetaModel.loaded().then(function () {
that.setModel(oMetaModel, "meta");
});
}
The interesting part is how to access stuff:
const sBasePath = "/dataServices/schema/[${namespace}===\'NAME_OF_YOUR_ODATA_SRV\']/entityType/[${name}===\'NameOfYourEntity\']"
const oEntityInformation = oMetaModel.getProperty(sBasePath);
const aKeys = oMetaModel.getProperty(sBasePath + "/key/propertyRef");
const aAllProperties = oMetaModel.getProperty(sBasePath + "/property");
const oSingleProperty = oMetaModel.getProperty(sBasePath + "/property/[${name}===\'NameOfYourProperty\']");
You can even access the model in your XML view:
columns="{
path: 'meta>/dataServices/schema/[${namespace}===\'NAME_OF_YOUR_ODATA_SRV\']/entityType/[${name}===\'NameOfYourEntity\']/property',
factory: '.columnFactory'
}"
Note that NameOfYourEntity has to be the name of the single Entity, so there is no Set at the end.
Not sure, what you want exactly but this script will write the metadata in JSON format in a blob. The save dialog in browser appears after that.
var oDataModel = this.getOwnerComponent().getModel();
oDataModel.attachMetadataLoaded(null, function() {
var oMetaData = oDataModel.getServiceMetadata(); //Read the metadata
var blob = new Blob([JSON.stringify(oMetaData)], {
type: "text/plain;charset=utf-8"
}); //Create a blob with metadata string in JSON format
if (navigator.msSaveBlob) {
return navigator.msSaveBlob(blob, "metadata.json"); //For IE
} else {
//For Chrome and FF we create a Link with a download attribute and trigger the click on it
var sUrl = URL.createObjectURL(blob); //Create the URL for the blob object
var oLink = document.createElement("a"); //Create link element
oLink.download = "metadata.json" //Set download attribute for link
oLink.href = sUrl; //Set href attribute for link
document.body.appendChild(oLink); //Append link to body
oLink.click(); //Click on link
oLink.remove(); //Remove link
}
});

get value for specific question/item in a Google Form using Google App Script in an on submit event

I have figured out how to run a Google App Script project/function on a form submit using the information at https://developers.google.com/apps-script/guides/triggers/events#form-submit_4.
Once I have e I can call e.response to get a FormResponse object and then call getItemResponses() to get an array of all of the responses.
Without iterating through the array and checking each one, is there a way to find the ItemResponse for a specific question?
I see getResponseForItem(item) but it looks like I have to somehow create an Item first?
Can I some how use e.source to get the Form object and then find the Item by question, without iterating through all of them, so I could get the Item object I can use with getResponseForItem(item)?
This is the code I use to pull the current set of answers into a object, so the most current response for the question Your Name becomes form.yourName which I found to be the easiest way to find responses by question:
function objectifyForm() {
//Makes the form info into an object
var myform = FormApp.getActiveForm();
var formResponses = myform.getResponses()
var currentResponse = formResponses[formResponses.length-1];
var responseArray = currentResponse.getItemResponses()
var form = {};
form.user = currentResponse.getRespondentEmail(); //requires collect email addresses to be turned on or is undefined.
form.timestamp = currentResponse.getTimestamp();
form.formName = myform.getTitle();
for (var i = 0; i < responseArray.length; i++){
var response = responseArray[i].getResponse();
var item = responseArray[i].getItem().getTitle();
var item = camelize(item);
form[item] = response;
}
return form;
}
function camelize(str) {
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()#\+\?><\[\]\+]/g, '')
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
//Use with installable trigger
function onSubmittedForm() {
var form = objectifyForm();
Logger.log(form);
//Put Code here
}
A couple of important things.
If you change the question on the form, you will need to update your
code
Non required questions may or may not have answers, so check if answer exists before you use it
I only use installable triggers, so I know it works with those. Not sure about with simple triggers
You can see the form object by opening the logs, which is useful for finding the object names

Setting URL in UploadCollectionItem in UI5 1.38.4

What parameters are mandatory for an UploadCollectionItem with the URL parameter set will show the file when the filename is clicked.
I am using a factory to handle files coming from different locations.
attachmentFactory(sId, context) {
const modelObj = context.getModel().getProperty(context.getPath());
const uploadListItem = new SAPUploadCollectionItem();
// If __metadata exists, attachment entry is from odata, if not then it's a FileEntry object.
if (modelObj.__metadata) {
uploadListItem.setFileName(modelObj.FILE_NAME);
uploadListItem.setMimeType(modelObj.MIME_CODE);
uploadListItem.setUrl("https://upload.wikimedia.org/wikipedia/commons/4/49/Koala_climbing_tree.jpg");
}
else {
uploadListItem.setFileName(modelObj.name);
uploadListItem.setMimeType(modelObj.type);
uploadListItem.setUrl("https://upload.wikimedia.org/wikipedia/commons/4/49/Koala_climbing_tree.jpg");
}
return uploadListItem;
}
I get an exception in UI5 when I press the link in the function
UploadCollection.prototype._triggerLink = function(oEvent, oContext) {
var iLine = null;
var aId;
if (oContext.editModeItem) {
//In case there is a list item in edit mode, the edit mode has to be finished first.
sap.m.UploadCollection.prototype._handleOk(oEvent, oContext, oContext.editModeItem, true);
if (oContext.sErrorState === "Error") {
//If there is an error, the link of the list item must not be triggered.
return this;
}
oContext.sFocusId = oEvent.getParameter("id");
}
aId = oEvent.oSource.getId().split("-");
iLine = aId[aId.length - 2];
sap.m.URLHelper.redirect(oContext.aItems[iLine].getProperty("url"), true);
};
oContext.aItems is an array but the source.getId() value is "__item9-ta_filenameHL" so __item9 is not found in oContext.aItems
I'm not sure if this is a bug or I'm setting up my UploadCollectionItem incorrectly
I had to set the sId of the UploadCollectionItem to be the sId that was passed into the factory.

arc-jsapi How can I st_geometry using a lookup field?

I am using the st_geometry field and try to view the PNU code value.
I tried two ways.
oracle DB query.
select a.pnu from LP_PA_CBND_4600000000 a
where sde.st_contains(a.shape,
sde.st_point(177566.6728471977,160430.12935426735, 4))=1
When an event occurs, click the map object
i got the evt.mapPoint(x,y).
4 is my srid.
this way is took a long time. and query was down...
i used the arcgis api`s IdentifyParameters
my code is follows.
PoiClick : function(map, evt) {
G_evt =evt;
console.log("ClickPoint ==== "+evt.mapPoint);
var targetLayerId = 'LP_PA_CBND';
var url = map.Layers.getLayerInfo(targetLayerId).SVC_URL;
var map = map.getMap();
//파라미터 설정.
var idParams = new krcgis.core.tasks.IdentifyParameters();
G_idparams =idParams;
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.returnGeometry = true;
idParams.tolerance = 3;
idParams.layerOption = krcgis.core.tasks.IdentifyParameters.LAYER_OPTION_ALL;
idParams.width = map.width;
idParams.height = map.height;
krcgis.Function.GetPoiInfo(url, idParams);
return evt.mapPoint;
},
//POI 정보를 가져온다.
GetPoiInfo : function(url, idParams) {
idTask = new krcgis.core.tasks.IdentyfyTask(url);
idTask
.execute(idParams)
.addCallback(function (response) {
G_response = response;
if (response) {
return response;
}
})
.addErrback(function (error) {
console.log('GetPoiInfo result error=', error);
});
}
It could be obtained in this way code pnu.
However, this way is different from the value that gets pnu code depending on the zoom level.
I want to get a single pnu code in a single x, y values.
how to get pnu code?
Database table :
IdentifyTask can be a little tricky, because it takes into account zoom levels, therefor it doesn't always return the same results.
I suggest that you use QueryTask. Just one problem - it doesn't have tolerance parameter, but you can buffer your evt.mapPoint and get Polygon.