SuiteScript New NetSuite UI InlineHTML elements not available in Javascript - netsuite

On the new NetSuite UI, when creating a Project Task from the Project Subtab, the script does not seem to load as expected.
On before load of my script I add an inlineHTML field to the form and insert them html.
for(var key in fieldIds) {
var html = "<span class='smallgraytextnolink uir-label'>"+
"<span class='smallgraytextnolink labelSpanEdit'>"+
"<a class='smallgraytextnolink'>"+originalField.label + "</a>"+
"</span>"+
"</span>"+
"<div id='" + fieldIds[key] + "_div'></div>";
var theField = form.addField("custpage_"+fieldIds[key]+"_canvasfield", "inlinehtml", "Redacted");
nlapiSetFieldValue("custpage_"+fieldIds[key]+"_canvasfield", html);
}
On client side, PageInit I use
var field = document.querySelector("#" + id + "_div");
to try and select the div element added into the inlineHTML, but unfortunately this returns null.
This all works in the old NetSuite UI.

If that worked in the past then it was a bug.
The way to set the value of an added field in the beforeLoad user event in which it is created is via its defaultvalue:
form.addField({
id:'custpage_lint_results',
type:ui.FieldType.INLINEHTML,
label:'Lint Results',
container:'custgrp_lint'
}).defaultValue = '<div id="lint_results"></div>';
or in SS1:
var msg = form.addField('custpage_ra_reject', 'inlinehtml');
msg.setLayoutType('outsideabove', 'startrow');
msg.setDefaultValue('<div id="lint_results"></div>');
In the pageInit you may have to fully qualify the document element. I've had some friction with this in the past though not recently:
var field = window.document.querySelector("#" + id + "_div");
Finally you may need to wait.
I haven't had any issues with querying an id set in an Inline Html field in the then() of a promise that is called from a pageInit but I have sometimes done the following in a pageInit because of what you are seeing:
function pageInit(){
var elem = null;
function doStart(){
elem = document.querySelector('#elemFromUE');
if(!elem) setTimeout(doStart, 200);
}
doStart();
...
}

Related

Viewing file properties instead of file in SharePoint document library

I have a document library on SharePoint online with lots of columns for metadata. These columns won't fit in a single view on screen, so I want the users to first view the properties of the file before downloading them.
Is there a way to change the behavior of the SharePoint library ensure that the user views the file properties first when they click on the filename?
PS: I understand I could have used lists, but after loading about 10000 documents, I have decided to use it as a last resort. Thank you.
Custom the LinkFilename field by CSR.
Sample code:
(function () {
'use strict';
var CustomWidthCtx = {};
/**
* Initialization
*/
function init() {
CustomWidthCtx.Templates = {};
CustomWidthCtx.Templates.Fields = {
'LinkFilename': {
'View': customDisplay
}
};
// Register the custom template
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(CustomWidthCtx);
}
/**
* Rendering template
*/
function customDisplay(ctx) {
var currentVal = '';
//from the context get the current item and it's value
if (ctx != null && ctx.CurrentItem != null)
currentVal = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
var el = "<div class='ms-vb itx' id='" + ctx.CurrentItem.ID + "' app='' ctxname='ctx37'><a title='" + ctx.CurrentItem._ShortcutUrl + "' class='ms-listlink ms-draggable' aria-label='Shortcut file' onfocus='OnLink(this)' href='/Doc4/Forms/EditForm.aspx?ID=" + ctx.CurrentItem.ID + "' target='_blank' DragId='17'>" + ctx.CurrentItem.FileLeafRef + "</a></div>";
// Render the HTML5 file input in place of the OOTB
return el;
}
// Run our intiialization
init();
})();

How to get a list of internal id in netsuite

Is there a proper way to get a list of all internal id in a Netsuite Record?
var record = nlapiLoadRecord('customer', 1249);
var string = JSON.stringify(record);
nlapiLogExecution('DEBUG', 'string ', string );
I can get most of the id using json string but i am looking for a proper way. It prints all the data including internal id. Is there any Api or any other way ?
I actually developed a Chrome extension that displays this information in a convenient pop-up.
I ran into the same issue of nlobjRecord not stringifying properly, and what I ended up doing was manually requesting and parsing the same AJAX page NS uses internally when you call nlapiLoadRecord()
var id = nlapiGetRecordId();
var type = nlapiGetRecordType();
var url = '/app/common/scripting/nlapihandler.nl';
var payload = '<nlapiRequest type="nlapiLoadRecord" id="' + id + '" recordType="' + type + '"/>';
var response = nlapiRequestURL(url, payload);
nlapiLogExecution('debug', response.getBody());
You can have a look at the full source code on GitHub
https://github.com/michoelchaikin/netsuite-field-explorer/
The getAllFields() function will return an array of all field names, standard and custom, for a given record.
var customer = nlapiLoadRecord('customer', 5069);
var fields = customer.getAllFields();
fields.forEach(function(field) {
nlapiLogExecution('debug', field);
})

Need to get the data of span using protractor

I want to get the id=2504 which is in html span using protractor and display it in the console log. This id is generated dynamically so the id number can be different all the time.My code looks like :
<span class="link ng-binding" ng-click="openTrackId(mapFeedBack.reportId)">Your tracking number is 2504</span>
Please advise how can i achieve it?
You can use regex to extract numbers from a string. Look at below example code.
var id = element(by.css("span.link")).getText().then(function(text){
return text.replace(/[^0-9]+/g, "");
})
In the span text if the ID is the last thing written you can do
var textTokens = text.split(" ");
var Id = textTokens[textTokens.length - 1];
console.log(Id);
Using protractor you can do
element.all(by.tagName('span').get(0).getText().then(function(text){
textTokens = text.split(" ");
var Id = textTokens[textTokens - 1];
console.log(Id);
});
Note if you have multiple spans you can put the above code in a loop and display the Id for each span element in your console.
element.all(by.tagName('span').count().then(function(spanCount){
for (var i = 0; i < spanCount; i++){
element.all(by.tagName('span').get(i).getText().then(function(text){
textTokens = text.split(" ");
var Id = textTokens[textTokens - 1];
console.log(Id);
});
}
});

Displaying list of all items with the same lookup fields in Display Form of that Lookup field in SharePoint 2013

I have 2 lists which are Room and Equipment.
In the Equipment list there is a lookup Field to the Room list .
I want to display all related Equipment in Room simple tabular Display Form.
How should I achieve this?
A general solution would be as follow
Check you can work with the REST API in JavaScript like below. (in this step you can just make sure the URL is returning XML data you requested)
http://portal/_api/web/lists/getByTitle('Equipments')/items/?$select=Title,ID&$filter=Room eq 'room1'
create a new custom DisplayForm with SharePoint Designer and add the following jQuery Script to read and generate the previous fetched data at the end of
<script src="/_layouts/15/CDN/Js/jquery-1.11.1.min.js" type="text/javascript" > </script>
<script type="text/javascript" >
function LoadEquipments(roomValue) {
$.ajax({
url : _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getByTitle('Equipments')/items/" +
"?$select=Title,ID" +
"&$filter=Room eq '" + roomValue + "'",
type : "GET",
headers : {
"accept" : "application/json;odata=verbose",
},
success : function (data) {
var equipments = [];
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
if (equipments.indexOf(results[i].Title) < 0)
equipments.push(results[i].Title);
}
var ullist = $('<ul/>');
for (var i = 0; i < equipments.length; i++)
$('<li/>').val(equipments[i]).html(equipments[i]).appendTo(ullist);
ullist.appendTo('#divEquipements');
$("#divEquipements ul li").css("font-size", "16px").css("color", "salmon");
},
error : function (err) {
alert(JSON.stringify(err));
}
});
}
$(document).ready(function () {
var roomVal = $("#TitleValue").text();
LoadEquipments(roomVal);
});
for previous code to work as you might guess you would better add id for new td to enclose the new requirements(for example a new tr as the last row which contains aa div with id='divEquipements' ) data and also just add id='TitleValue' to the td containing the room title (usually the first row)
OK there are a lot of possibilities for achieving this. Some possible and good looking solution can be:
Overload the click of the market value in the list(can be done using JSLink) to open a Modal dialog page where all the equipments are listed(fetched using REST query)
Overload the click of the market value in the list(can be done using JSLink) and redirect to the same page but with filters to the same view.
If the number of markets are not many, views can also be created per market(Not so good, but will reduce coding effort)
If its something else you are looking for, please let know. Hope this helps!

SharePoint 2013 - Get SPListItem versions via REST

I have a SharePoint 2013 List with versioning enabled.
I need to to get SPListItem versions list via REST.
I can get SPListItem by that request: http://spbreportportal/Projects/_api/lists/getbytitle('Projects')/Items(1)
But I can't find in documentation and in response how to retrieve all versions of this item.
Is it possible?
It does not seem possible to get versions for a List Item via REST/CSOM APIs, but there are alternative options
Using Versions.aspx application page
The idea is to perform a get request to Versions page: http://<server>/<site>/_layouts/versions.aspx?list={litsID}&ID=<itemID>
function getItemVersions(url,listId,itemId,success)
{
var versionsUrl = url + '/_layouts/versions.aspx?list=' + listId + '&ID=' + itemId;
$.get( versionsUrl, function( data ) {
var versionEntries = parseVersionList(data);
success(versionEntries);
});
}
function parseVersionList(data){
var entries = {};
var versionList = $(data).find('table.ms-settingsframe');
versionList.find('tbody > tr').each(function(i){
if(i > 0 && (i-1) % 2 == 0) {
var verRow = $(this); //get version row
var propsRow = verRow.next(); //get properties row
var versionLabel = verRow.find('td:first').html().trim();
entries[versionLabel] = {};
//extract item properties from propsRow goes here
//...
}
});
return entries;
}
//Usage
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var listId = _spPageContextInfo.pageListId;
var listItemId = 1;
getItemVersions(webUrl,listId,listItemId,function(versionEntries){
console.log(versionEntries);
});
Using Lists SharePoint Web Services
Another option would be to utilize Lists SharePoint Web Services that exposes Lists.GetVersionCollection Method to return version information for the specified field in a SharePoint list
SPServices example:
$().SPServices({
operation: "GetVersionCollection",
async: false,
strlistID: "Projects",
strlistItemID: 1,
strFieldName: "Description",
completefunc: function (xData, Status) {
$(xData.responseText).find("Version").each(function(i) {
console.log("Name: " + $(this).attr("Description") + " Modified: " + $(this).attr("Modified"));
});
}
});
Note: This doesn't seem to work in 2013. I have verified this working in SharePoint Online and it may work in 2016+ but I have not verified the latter.
The situation may have changed since this question was originally posted, but it is now possible to use the REST API to get version history for any list/library item:
https://url/to/site/_api/web/Lists/getbytitle('MyListName')/items(ITEMID)/versions
This will return a series of results for the current version and all past versions, with the item's column values from each version.
As with other REST endpoints, you can use $select, $filter, etc. to further manipulate the results.
In the REST API, you can select the property OData__UIVersionString. It also supports OData__ModerationStatus
Ex:
GET http://site url/_api/web/lists/GetByTitle(‘Test')/items(item id)?$select=OData__UIVersionString,OData__ModerationStatus
More infos : https://msdn.microsoft.com/en-us/library/office/dn292552.aspx
It's not a solution to get all the versions or a specific version, but it's more info on the version.
To add to #Vadim Gremyachev's Excellent answer to use "GetversionCollection": This interface can also be reached using old school SOAP. Unfortunately it only returns one field at the time (so we use a lot of calls ...). The C# snippet is below.
//https://blogs.msdn.microsoft.com/pinch-perfect/2016/06/04/sharepoint-web-services-read-version-history-for-column-changes/
//http://www.indy.gov/eGov/City/DCE/Permits/Signs/_vti_bin/lists.asmx?op=GetVersionCollection
//https://www.codeproject.com/Articles/26338/Using-the-GetListItems-GetVersionCollection-and-Up
string strSite =
string strListGuid =
string strListItemID =
string strFieldName = "Title" // or some other field name
string requestXML = "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:Body>" +
"<GetVersionCollection xmlns='http://schemas.microsoft.com/sharepoint/soap/'>" +
"<strlistID>"+ strListGuid + "</strlistID><strlistItemID>" + strListItemID + "</strlistItemID>" +
"<strFieldName>"+ strFieldName +"</strFieldName>" +
"</GetVersionCollection>" +
"</soap:Body>" +
"</soap:Envelope>";
object xmlRequestObj = Activator.CreateInstance(Type.GetTypeFromProgID("Microsoft.XMLHTTP"));
MSXML2.XMLHTTP xmlRequest = (MSXML2.XMLHTTP)xmlRequestObj;
xmlRequest.open("Get", strSite + "/_vti_bin/Lists.asmx", false, null, null);
xmlRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetVersionCollection");
xmlRequest.send(requestXML);
string responseText = xmlRequest.responseText;
To add more information reagrding on how to obtain all version history from a SharePoint list:
//Get ID of the Dossier in SP list
strID = items(i - 1).getAttribute("ows_ID")
Debug.Print strID
//Get all Versions of the ID in SP list as a XML
URL1: https://path to site collection/_vti_bin/owssvr.dll?Cmd=Display&List={LIstID}&XMLDATA=TRUE&Query=*&IncludeVersions=TRUE
XDoc3.Load (URL1 & "&FilterField1=ID&FilterOp1=eq&FilterValue1=" & strID)
Set Item = XDoc3.SelectNodes("//rs:data/*")
Set temp3 = XDoc3.SelectNodes("//rs:data/*")

Resources