Alfresco: Javascript data list creation - javascript

I am attempting to execute some Javascript in my Alfresco workflow to create a custom data list type in my site called "Testing". But before I fill in my custom data list type information, I tried simply creating a contact list data list based on examples I found to make sure it works.
Here is my code:
var site = siteService.getSite("Testing");
var dataLists = site.childByNamePath("dataLists");
if (!dataLists) {
var dataLists = site.createNode("dataLists", "cm:folder");
var dataListProps = new Array(1);
dataListProps["st:componentId"] = "dataLists";
dataLists.addAspect("st:siteContainer", dataListProps);
dataLists.save();
logger.log("Created new datalists folder.");'
}
var contactList = dataLists.childByNamePath("contactlist1");
if (!contactList) {
var contactList = dataLists.createNode("contactlist1","dl:dataList");
// tells Share which type of items to create
contactList.properties["dl:dataListItemType"] = "dl:contact";
contactList.save();
var contactListProps = [];
contactListProps["cm:title"] = "My Contacts";
contactListProps["cm:description"] = "A contact list generated by a javascript.";
contactList.addAspect("cm:titled", contactListProps);
logger.log("Created contact datalist.");
}
var contact = contactList.createNode(null, "dl:contact")
contact.properties["dl:contactFirstName"] = "Florian";
contact.properties["dl:contactLastName"] = "Maul";
contact.properties["dl:contactEmail"] = "info#fme.de";
contact.properties["dl:contactCompany"] = "fme AG";
contact.properties["dl:contactJobTitle"] = "Senior Consultant";
contact.properties["dl:contactPhoneMobile"] = "not available";
contact.properties["dl:contactPhoneOffice"] = "not available";
contact.properties["dl:contactNotes"] = "Alfresco Expert";
contact.save();
logger.log("Created new contact: " + contact.nodeRef);
My guess is it's not selecting the right site, but I'm not sure how else to set the site variable to the "Testing" site. Also, I know this code is in the right place in my .bpmn file, because other Javascript in there executes correctly.
What is wrong with my code?

There are 2 javascript object on which you have confusion.One is site and other is node.Site object does not have method called childByNamePath.
Instead of that use below for getting datalist.
var dataLists = site.getContainer("dataLists");
Your code for retrieving site is correct.The only change is for datalist.

Related

Can I use two parameter event for one function?

What I want to do is change the url.
Replace the Object word with an event parameter called e1.
Replace the word field with the event parameter e2.
I know this code is not working.
But I don't know how to do it.
The following is my code that I just wrote.
function getAllFieldValue(e1,e2) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var url = 'test123.my.salesforce.com/services/data/v44.0/queryAll?q=SELECT Field FROM Object';
var url = url.replace('Object',e1);
var url = url.replace('Field',e2);
var response = UrlFetchApp.fetch(url,getUrlFetchOptions());
var json = response.getContentText();
var data = JSON.parse(json);
var fieldValues = data.records;
for(var i=0;i<fieldValues.length;i++){
var fieldValue = fieldValues[i].e;
ss.getRange(i+1,1).setValue(fieldValue);
}
}
I want to take the data from another database through this code and put it in the Google spreadsheet.
For e1, it means the object value selected in the dropbox.
For e2, it means the field of the object selected in the drop box.
Is there a way to use two event parameters for one function?
I look forward to hearing from you.
====================
Please understand that I am using a translator because I am not good at English.
Checking fieldValues[i] in Logger.log returns the following values:
[{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03VAAT
},
Name=University of Arizona
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03TAAT
},
Name=United Oil & Gas Corp.
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03ZAAT
},
Name=sForce
}]
The issues I am currently experiencing are as follows.
If I select 'Name' from the drop-down list, ec2 becomes 'Name'.
As far as I'm concerned,
var fieldName = fieldValues[i].e2 is
var fieldName = fieldValues[i].Name
It means that.
I think fieldValues[i].e2 should return the values of University of Arizona, United Oil & Gas Corp, sForce.
But in reality nothing is returned.
var fieldName = fieldValues[i].Name works properly.
I think there is a problem with fieldValues[i].e2
This is the problem I'm currently experiencing.
There was no problem with the parameters e1, e2, which I thought was a problem. The reason why the code did not work is because of the for loop var fieldValue = fieldValues[i].e; Because it didn't work properly.
var fieldName = fieldValues[i].e2
to
var fieldName = fieldValues[i][e2]
After modifying it like this, the code works properly.

Creating a Function to Process an RSS Feed in Google Sheets

I am trying to create a function that I can import into Google Sheets to view the latest bills from this website. A problem that I am having is that when I create only one variable to be appended to the Google Sheet this code will work and append the first cell. But when I create multiple variables using the same logic, but for different parts of the xml file that this link brings you to, it gives me this error even when I create completely different variables for the original document and root: TypeError: Cannot read property 'getValue' of null. Would anyone be able to show me what I am doing wrong so that I can at least get it so that all of these items can be appended to the Google Sheet through solving for this error and show me a way to do a loop to get all these items?
function getData() {
//get the data from boardgamegeek
var url = 'https://legis.delaware.gov/rss/RssFeeds/IntroducedLegislation';
var xmlrss = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(xmlrss);
var root = document.getRootElement();
//Clear out existing content
var sheet = SpreadsheetApp.getActiveSheet();
var rangesAddressesList = ['A:F'];
sheet.getRangeList(rangesAddressesList).clearContent();
//set variables to data from rss feed
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var title = root.getChild('channel').getChild('item').getChild('title').getText();
var session = root.getChild('channel').getChild('item').getChild('derss:legislativeSession').getText();
var link = root.getChild('channel').getChild('item').getChild('link').getText();
var category = root.getChild('channel').getChild('item').getChild('category').getText();
var description = root.getChild('channel').getChild('item').getChild('description').getText();
var pubDate = root.getChild('channel').getChild('item').getChild('pubDate').getText();
sheet.appendRow(["Session", "Title", "Category", "Pub Date", "Description", "Link"]);
sheet.appendRow([session, title, category, pubDate, description, link]);
}
I believe your goal as follows.
You want to retrieve the values of legislativeSession, title, category, pubDate, description, link in order using Google Apps Script.
You want to put the retrieved values to Google Spreadsheet.
Modification points:
In the case of derss:legislativeSession, derss is the name space. So in this case, it is required to use the name space.
When I saw your XML data, there are many item tags. But in your script, 1st item is trying to be retrieved.
When the values from all items are retrieved, when appendRow is used in a loop, the process cost will become high.
When above points are reflected to your script, it becomes as follows.
Modified script:
function getData() {
var url = 'https://legis.delaware.gov/rss/RssFeeds/IntroducedLegislation';
var xmlrss = UrlFetchApp.fetch(url).getContentText();
// Set the object for retrieving values in order.
var retrieveNames = {legislativeSession: "Session", title: "Title", category: "Category", pubDate: "PubDate", description: "Description", link: "Link"};
// Parse XML data.
var document = XmlService.parse(xmlrss);
var root = document.getRootElement();
// Retrieve itmes.
var item = root.getChild('channel').getChildren("item");
// Retrieve name space of "derss".
var derssNs = root.getChild('channel').getNamespace("derss");
// By retrieving values from each item, create an array for putting values to Spreadsheet.
var values = item.reduce((ar, e) => ar.concat(
[Object.keys(retrieveNames).map(k => e.getChild(...(k == "legislativeSession" ? [k, derssNs] : [k])).getText())]
), [Object.values(retrieveNames)]);
// Put the created array to Spreadsheet.
var sheet = SpreadsheetApp.getActiveSheet();
var rangesAddressesList = ['A:F'];
sheet.getRangeList(rangesAddressesList).clearContent();
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}
In this modified script, it supposes that the active sheet is the 1st sheet. If your actual situation is different, please modify above script.
References:
XML Service
reduce()

Updating SP.ListItem with SP.Field Value from SP.PeoplePicker

Im trying to update an SP.Listitem withholding an spUser with another user with the use of JSOM. See codesnippet bellow
// Query the picker for user information.
$.fn.getUserInfo2 = function () {
var eleId = $(this).attr('id');
var siteUrl = _spPageContextInfo.siteServerRelativeUrl;
var spUsersInfo = GetPeoplePickerValues(eleId);
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('VLS-dokument');
var itemArray = [];
for(i=0;i<$.miniMenu.i.results.length;i++)
{
var item = $.miniMenu.i.results[i];
var oListItem = oList.getItemById(item.Id);
oListItem.set_item('Informationsägare', SP.FieldUserValue.fromUser(spUsersInfo.Key));
oListItem.update();
itemArray.push(oListItem);
clientContext.Load(itemArray[itemArray.Length - 1]);
}
clientContext.executeQueryAsync(Function.createDelegate(this, function () { alert(""); }), Function.createDelegate(this, function () { alert(""); }));
return spUsersInfo; //.slice(0, -2)
}
spUsersInfo contains the user obj, peoplePicker.GetAllUserInfo()
The return off SP.FieldUserValue.fromUser(spUsersInfo.Key) to be the problem since the app crash reaching that line oListItem.set_item('Informationsägare', SP.FieldUserValue.fromUser(spUsersInfo.Key));
What part of the user obj is supposed to be passed into SP.FieldUserValue.fromUser(spUsersInfo.Key) if not the key?
Is there another way to do it?
People picker columns are really just lookup columns, looking up against the site collection's user information list. You can set a lookup column either by specifying the ID of the desired item in the lookup list, or by creating a special lookup field value object (letting SharePoint do the work of finding the ID, given the desired text value).
According to the documentation the value passed to SP.FieldUserValue.fromUser() should be the user's name as a string. In practice, this should be the user's display name from the user information list.
So if you don't know the user's lookup ID, but do know their display name, you would use this: oListItem.set_item('Informationsägare',SP.FieldUserValue.fromUser(username));
If you didn't know the user name, but did know the lookup ID of the user, you could instead pass that number to item.set_item() directly, i.e. oListItem.set_item('Informationsägare',lookupId);.
If the spUsersInfo.Key value from your GetPeoplePickers() method is in the format of i:0#.w|Cool Person then you can split that value and just get the string Cool Person to feed into SP.FieldUserValue.fromUser().

Alfresco: update data list line

I have data being sent to a custom data list from the following code:
// Get the site name and dataLists
var site = siteService.getSite("Testing");
var dataLists = site.getContainer("dataLists");
// Check for data list existence
if (!dataLists) {
var dataLists = site.createNode("dataLists", "cm:folder");
var dataListProps = new Array(1);
dataListProps["st:componentId"] = "dataLists";
dataLists.addAspect("st:siteContainer", dataListProps);
dataLists.save();
}
// Create new data list variable
var orpList = dataLists.childByNamePath("orplist1");
// If the data list hasn't been created yet, create it
if (!orpList) {
var orpList = dataLists.createNode("orplist1","dl:dataList");
// Tells Alfresco share which type of items to create
orpList.properties["dl:dataListItemType"] = "orpdl:orpList";
orpList.save();
var orpListProps = [];
orpListProps["cm:title"] = "Opportunity Registrations: In Progress";
orpListProps["cm:description"] = "Opportunity registrations that are out for review.";
orpList.addAspect("cm:titled", orpListProps);
}
// Create new item in the data list and populate it
var opportunity = orpList.createNode(execution.getVariable("orpWorkflow_nodeName"), "orpdl:orpList");
opportunity.properties["orpdl:nodeName"] = orpWorkflow_nodeName;
opportunity.properties["orpdl:dateSubmitted"] = Date().toString();
opportunity.properties["orpdl:submissionStatus"] = "Requires Revisions";
opportunity.save();
This correctly creates data list items, however, at other steps of the workflow require these items to be updated. I have thought of the following options:
Remove the data list item and add another with the updated information
Simply update the data list item
Unfortunately I have not found adequate solutions elsewhere to either of these options. I attempted to use orpWorkflow_nodeName, which is a unique identifier generated at another step, to identify a node to find it. This does not seem to work. I am also aware that nodes have unique identifiers generated by Alfresco itself, but documentation doesn't give adequate information on how to obtain and use this.
My question:
Instead of var opportunity = orpList.createNode(), what must I use in
place of createNode() to identify an existing node so I can update its
properties?
You can use this to check existing datalist item.
var opportunity = orpList .childByNamePath(execution.getVariable("orpWorkflow_nodeName"));
// If the data list Item is not been created yet, create it
if (!opportunity ) {
var orpList = orpList .createNode(execution.getVariable("orpWorkflow_nodeName"),"dl:dataList");}

Birt: access content of dataset from beforeFactory

Im trying (desperately) to access the content of a dataset by script in the beforeFactory.
The task at hand is to create design elements from a linked library and place them in a certain cell of a grid. Everything works fine except for the "place them in a certain cell of a grid"-part.
The information about which element is to be created and where it is to be placed is available in a dataset (dsDesignInformation), which contains three columns: targetRow, targetColumn, targetContent. targetContent contains a string, which is used to find an element in the library.
For example: There is a grid placed on the body (grdMasterGrid), with two rows and two columns. If the dsDesignInformation would contain a row like (1,1,"testObjectName"), I want to create the element "testObject" from a linked library and place it in the intersection of row 1 and column 1 of my grdMasterGrid.
The code for creating and placing the element:
importPackage(org.eclipse.birt.report.model.api);
var myLibraryHandle = reportContext.getDesignHandle().getLibrary("myLibraryName");
var myElementFactory = reportContext.getDesignHandle().getElementFactory();
// should be the objectname as defined in the dsDesignInformation
var myTargetElementHandle = myLibraryHandle.findElement("testObjectName");
var myCreatedElementHandle = myElementFactory.newElementFrom(myTargetElementHandle , "someUniqueElementName");
var myMasterGridHandle = reportContext.getDesignHandle().findElement("grdMasterGrid");
// should be target coordinates as defined in dsDesignInformation
var myTargetCellHandle= myMasterGridHandle.getCell(1,1);
myTargeCellHandle.getContent().add(myCreatedElementHandle);
This works like a charm when used with hard coded target-information and placed in the beforeFactory of the report design.
I do however need to access the contents of dsDesignInformation and pass them on to the script above. So far (4 days in) I had zero (as in null) success.
I would be glad for any help or ideas on the topic.
Regards,
maggutz
It is possible to do this, but with some severe restrictions.
The main restriction is: You cannot use your DataSource and your DataSet directly.
Instead, you'll have to copy them and work with the copy.
Don't ask my why this is, because I don't know. But I learned it the hard way during hours and days of trying...
The next restriction is: You cannot access report parameter values, unfortunately. This is not a problem if your query works without parameters.
Otherwise, you'll have to find a way to access the parameter value anyhow. Depending on how your report is integrated into the app, you could try writing the value into the appContext before calling BIRT, for example.
Here is a fragment of working code (in the beforeFactory event) to show you how to workaround this limitation:
importPackage( Packages.org.eclipse.birt.report.model.api );
importPackage(Packages.org.eclipse.birt.data.engine.api);
importPackage(Packages.org.eclipse.birt.report.model.api);
importPackage(Packages.org.eclipse.birt.data.engine.api.querydefn);
importPackage(Packages.org.eclipse.birt.data.engine.core);
importPackage( Packages.org.eclipse.birt.report.model.api );
var myconfig = reportContext.getReportRunnable().getReportEngine().getConfig();
var de = DataEngine.newDataEngine( myconfig, null );
var dsrc = reportContext.getDesignHandle().findDataSource("lisa");
// This is the existing data source.
var odaDataSource = new OdaDataSourceDesign( "Test Data Source" );
// We create a new DataSource which is only to be used in this event
// Now we copy the relevant properties from the existing DataSource to the new one.
var dbUrl = dsrc.getProperty("odaURL").toString();
var dbUsr = dsrc.getProperty("odaUser").toString();
var dbPwd = dsrc.getProperty("odaPassword").toString();
var dbDrv = dsrc.getProperty("odaDriverClass").toString();
odaDataSource.setExtensionID( "org.eclipse.birt.report.data.oda.jdbc" );
odaDataSource.addPublicProperty( "odaURL", dbUrl );
odaDataSource.addPublicProperty( "odaDriverClass", dbDrv);
odaDataSource.addPublicProperty( "odaUser", dbUsr );
odaDataSource.addPublicProperty( "odaPassword", dbPwd );
// log.info("odaURL=" + dbUrl); // Only if you have a logging framework at hand
// Now create a new DataSet and set its query etc.
// I suppose that it is possible to copy the properties from an existing DataSet instead.
// However, I didn't try that.
var odaDataSet = new OdaDataSetDesign( "Test Data Set" );
odaDataSet.setDataSource( odaDataSource.getName() );
odaDataSet.setExtensionID( "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet" );
// This is the SQL query (in my application).
// You'll have to modify this as needed.
odaDataSet.setQueryText( " select STEDA.TEDA_ID, STBST.LANGTEXT" +
" from STEDA, STBST" +
" where STEDA.ZUSATZ_1 = 'MATRIX'" +
" and STBST.TBST_ID = STEDA.TEDA_ID");
// Tell the DataEngine about the new objects.
de.defineDataSource( odaDataSource );
de.defineDataSet( odaDataSet );
// Now execute the query:
// This seems overly complicated, but hey: it works.
var queryDefinition = new QueryDefinition( );
queryDefinition.setDataSetName( odaDataSet.getName() );
queryDefinition.setAutoBinding(true);
var pq = de.prepare( queryDefinition );
var qr = pq.execute( null );
rowcount=0;
var elementFactory = reportContext.getDesignHandle().getElementFactory()
var ri = qr.getResultIterator( );
// Our application is using the query to generate a layout structure
// into an (already existing) placeholder element "Layout MATRIX".
var containerGrid = reportContext.getDesignHandle().findElement("Layout MATRIX");
// Iterate through the query results
while ( ri.next( ) )
{
// get the actual values of the query output columns
var tedaId = ri.getString("TEDA_ID");
var langtext = ri.getString("LANGTEXT");
// log.info("langtext: " + langtext);
rowcount++;
// Do something with the current result row.
... myModifyLayout(containerGrid, tedaId, langtext); ...
}
// Cleanup
ri.close( );
qr.close( );
de.shutdown( );
// You may want to save the modified design file while developing.
// That way you can check the mresults in the Report Designer.
if (false) {
reportContext.getDesignHandle().saveAs("c:/temp/modified.rptdesign");
}

Categories