SharePoint 2013 - JavaScript get URL from List - javascript

I am using the below JavaScript code to get the title of all lists in SharePoint 2013. How can i adapt this to return the URL of each list as well?
I've tired this but it doesn't work:
//listUrl = oList.get_url();
//console.log(listUrl);
Code:
function retrieveAllListProperties() {
var clientContext = new SP.ClientContext('/StrategicProjectOffice');
var oWebsite = clientContext.get_web();
this.collList = oWebsite.get_lists();
clientContext.load(collList);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded)
);
}
function onQuerySucceeded() {
var listTitle = '';
var listEnumerator = collList.getEnumerator();
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
listTitle = oList.get_title();
//listUrl = oList.get_url();
//console.log(listUrl);
if (listTitle.indexOf("SPO") >= 0) {
getItemsFromView(listTitle, "All Tasks");
}
}
}

List Url could be retrieved via SPList.RootFolder property, in your example the line:
clientContext.load(collList);
needs to be replaced with
clientContext.load(collList,'Include(RootFolder.ServerRelativeUrl)');
which tells to construct a query to return RootFolder.ServerRelativeUrl property of List object.
Example
Here is my version which retrieves lists and prints its url:
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
ctx.load(lists,'Include(RootFolder.ServerRelativeUrl)');
ctx.executeQueryAsync(
function () {
for(var i = 0; i < lists.get_count(); i++){
var list = lists.getItemAtIndex(i);
var listUrl = list.get_rootFolder().get_serverRelativeUrl();
console.log(listUrl);
}
},
function(sender,args){
console.log(args.get_message());
}
);

Related

How add a filter in server script with query

i'm new in servicenow and I have to add this filter "document_id.number STARTS WITH BKNG"
as a query, how can i do in servicenow?
this is my code:
// only show 30 in header menu dropdown
var max = 30;
var t = data;
t.items = [];
t.count = 0;
var u = getMyApprovals();
// use record watchers to tell header when to update dropdown counts
t.record_watchers = [];
t.record_watchers.push({'table':'sysapproval_approver','filter':'approverIN' + u.toString() + '^state=requested'});
var z = new GlideRecord('sysapproval_approver');
z.addQuery("approver", u);
z.addQuery("state", "requested");
z.addQuery("document_id.number", "STARTSWITH", "BKNG")
z.orderByDesc('sys_updated_on');
z.setLimit(max);
z.query();
var link = {};
link.title = gs.getMessage('View all approvals');
link.type = 'link';
link.href = '?id=approvals';
link.items = [];
t.items.push(link);
while (z.next()) {
var a = {};
var rec = getRecordBeingApproved(z);
if (!rec.isValidRecord()) // nothing being approved - hmmm
continue;
a.short_description = rec.short_description + "";
if (rec.getRecordClassName() == "sc_request") {
var items = new GlideRecord("sc_req_item");
items.addQuery("request", rec.getUniqueValue());
items.query();
if (items.getRowCount() > 1)
a.short_description = items.getRowCount() + " requested items";
else if (items.getRowCount() == 1) {
items.next();
a.short_description = items.getValue("short_description");
}
}
$sp.getRecordValues(a, z, 'sys_id,sys_updated_on');
a.number = rec.getDisplayValue();
a.__table = z.getRecordClassName();
a.type = 'approval';
t.items.push(a);
t.count++;
}
function getRecordBeingApproved(gr) {
if (!gr.sysapproval.nil())
return gr.sysapproval.getRefRecord();
return gr.document_id.getRefRecord();
}
i tried doing z.addQuery ("document_id.number", "STARTSWITH", "BKNG")
but it doesn't works.
i don't know how to do.
You can't dot-walk the document_id field when using .addQuery() as it is not a reference filed. Instead, you can use the Approval for (sysapproval) reference field like so:
z.addQuery("sysapproval.number", "STARTSWITH", "BKNG");

returning nested json values using loop (google spreadsheet)

I have this google spreadsheet script that pulls in json formatted book data. I have no problem displaying book title and author, but he "offerData" object can contain a different amount of elements (prices from sellers) depending on the book. Right now I created a loop and am storing the offerData values like so:
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
and am returning the data like this:
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
Obviously this only returns 3 sellers with price, condition, seller info. The issue is that a book doesn't always have 3 sellers, it can be anywhere from 1 to 10 or so.
My question is how can I return all offerData (price/condition/seller) here? :
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
--
function getBookDetails(isbn) {
// Query the book database by ISBN code.
if (isbn !== "") {
var url = "https://api.bol.com/catalog/v4/search/?apikey=myapi6&offers=all&format=json&q=" + isbn;
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response);
if (results.totalResultSize) {
// There'll be only 1 book per ISBN
var book = results.products[0];
// get Title and Authors
var title = (results.products[0]["title"]);
var specstag = (results.products[0]["specsTag"]);
var offerdata = results.products[0]["offerData"];
if (typeof offerdata.offers !== 'undefined' && offerdata.offers.length > 0) {
var arrayLength = offerdata.offers.length;
var price = [];
var condition = [];
var seller = [];
for (var i = 0; i < arrayLength; i++) {
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
}
}
}
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
return resultRow;
}
}
the answer
var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
resultRow[0][3*i+2]=price[i];
resultRow[0][3*i+3]=condition[i];
resultRow[0][3*i+4]=seller[i];
}
how you should think about it is to see the index of the elements in the array and then find relation between i and the index you want
var resultRow = [
[
title, //[0][0]
specstag, //[0][1]
price[0], //[0][2]
condition[0], //[0][3]
seller[0], //[0][4]
price[1], //[0][5]
condition[1], //[0][6]
seller[1], //[0][7]
price[2], //[0][8]
condition[2], //[0][9]
seller[2]//[0][10]
]
];
You might be looking for something like this;
var data = { title: null,
spcstag: null,
pcs: [],
};
offerData.offers.forEach( p => { var pcsData = {};
!!data.title || data.title = p.title;
!!data.specstag || data.specstag = p.specstag;
pcsData.price = p.price;
pcsData.condition = p.condition;
pcsData.seller = p.seller;
data.pcs.push(pcsData);
});

Push to This Workaround

I'm trying to refactor a portion of a Google AdWords script I've written in order to not have to repeat an if statement that I'm hoping I can dynamically update via an instance of "this". However, I'm receiving a "Cannot find function push in object firstKeywords. (line 34)" error. When I simply insert "firstKeywords.push", instead of "this.keywordsArray.push" the script works. Was wondering if there's a way to have the "this" instance be considered an array or if there's another work around?
Error: this.keywordsArray.push
Non-working script:
var firstKeywords = [];
var secondKeywords = [];
var thirdKeywords = [];
function main() {
function testKeywords(adgr, keywordsArray) {
this.adgr = adgr;
this.keywordsArray = keywordsArray;
}
testKeywords.prototype.move = function () {
var campaignIterator = AdWordsApp.campaigns()
.withCondition("Status = ENABLED")
.withCondition("Name CONTAINS_IGNORE_CASE 'High'")
.get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var adGroupIterator = campaign.adGroups()
.withCondition("Name CONTAINS_IGNORE_CASE 'Blogs'")
.get();
while (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var adGroupName = adGroup.getName();
var keywordIterator = adGroup.keywords()
.withCondition("SystemServingStatus = RARELY_SERVED")
.get();
while (keywordIterator.hasNext()) {
var keyword = keywordIterator.next();
var keywordText = keyword.getText();
var adgroupArray = this.keywordsArray;
if (adGroupName === this.adgr) {
this.keywordsArray.push(keywordText);
keyword.pause();
}
}
}
}
}
var test01 = new testKeywords("General Music Blogs", "firstKeywords");
var test02 = new testKeywords("Hip Hop Music Blogs", "secondKeywords");
var test03 = new testKeywords("Indie Music Blogs", "thirdKeywords");
test01.move();
test02.move();
test03.move();
}
The below script works the correct way, but with the if statements repeated.
var firstKeywords = [];
var secondKeywords = [];
var thirdKeywords = [];
function main() {
function testKeywords() {
var campaignIterator = AdWordsApp.campaigns()
.withCondition("Status = ENABLED")
.withCondition("Name CONTAINS_IGNORE_CASE 'High'")
.get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var adGroupIterator = campaign.adGroups()
.withCondition("Name CONTAINS_IGNORE_CASE 'Blogs'")
.get();
while (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var adGroupName = adGroup.getName();
var keywordIterator = adGroup.keywords()
.withCondition("SystemServingStatus = RARELY_SERVED")
.get();
while (keywordIterator.hasNext()) {
var keyword = keywordIterator.next();
var keywordText = keyword.getText()
if (adGroupName === 'General Music Blogs') {
firstKeywords.push(keywordText);
keyword.pause();
}
if (adGroupName === 'Hip Hop Music Blogs') {
secondKeywords.push(keywordText);
keyword.pause();
}
if (adGroupName === 'Indie Music Blogs') {
thirdKeywords.push(keywordText);
keyword.pause();
}
}
}
}
}
}
Thanks in advance.
In your testKeyword you are passing string literals and not the object refs.
So change
var test01 = new testKeywords("General Music Blogs", "firstKeywords");
var test02 = new testKeywords("Hip Hop Music Blogs", "secondKeywords");
var test03 = new testKeywords("Indie Music Blogs", "thirdKeywords");
to
var test01 = new testKeywords("General Music Blogs", firstKeywords);
var test02 = new testKeywords("Hip Hop Music Blogs", secondKeywords);
var test03 = new testKeywords("Indie Music Blogs", thirdKeywords);

Win Pivot App. Need to access some data from a section. Any ideas?

I have a JavaScript Win Pivot Application
Into the Hub I am retrieving some information:
function initPages(options) {
for (var i = 0; i < options.length ; i++) {
var menuItem = options[i];
menuItem.showBanner = (i == 0);
definePages(options);
}
}
and in a .Js file I have the definePages function created:
functions.js:
function definePages(item) {
var action = item[0];
var animation = item[1];
var scyfy = item[2];
var localmovies = item[3];
var clasic = item[4];
var comedy = item[5];
var biography = item[6];
var drama = item[7];
var kids = item[8];
var musical = item[9];
var romantic = item[10];
var suspense = item[11];
var horror = item[12];
var art = item[13];
var personalities = item[14];
var history = item[15];
var society = item[16];
}
Now, in my section 1 I initialize the page by calling another function there:
ready: function (element, options) {
// TODO: Inicializar la página aquí.
options = options || {};
initMovies();
},
function initMovies() {
var element = document.getElementById("movieContainer");
//var movies = ??????????????????????????
//console.log(movies);
//it keeps going
}
I need to be able to retrive, in that var movies, the var action, from the functions.Js or, which is the same, the items[0]...
However, if I call a function in functions.Js, which is defined in section1Page, it won´t work...
I can call functions and pass data from anywhere to functions.Js, but not the other way around...
Any ideas on what should I do? Thanks!!!
I fixed it... I created a global var in function.Js and I get the info from the array in each section later on:
function definePages(item) {
tooSleepyToThink = item;
}
section1Page:
function initMovies() {
var elemento = document.getElementById("movieContainer");
console.log(tooSleepyToThink[0].text);
}

Process multiple sharepoint list items

in a SharePoint list view I would like to duplicate selected list items. My code works when only one item selected but fails, when more. Debugging the code I see that it goes through all selected items first before calls the success callback. Also within the success callback the currItem not always filled with the item data.
How can I get and process the selected items one-by-one?
function copySelected(){
if($("#copyAllButton").hasClass('ms-cui-disabled')){
return;
}
var cc = null;
var web = null;
copyCounter = 0;
failedCounter = 0;
cc = new SP.ClientContext.get_current();
web = cc.get_web();
var currItem = null;
notifyId = SP.UI.Notify.addNotification(duplicatingItemsNotification, true);
var selectedItems;
currList = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList());
selectedItems = SP.ListOperation.Selection.getSelectedItems();
if( selectedItems.length > 0 ){
for(var i in selectedItems){
//var currItemID = selectedItems[i].id;
currItem = currList.getItemById(selectedItems[i].id);
cc.load(currItem);
cc.executeQueryAsync(function(sender, args){
var itemCreateInfo = new SP.ListItemCreationInformation();
var aListItem = currList.addItem(itemCreateInfo);
aListItem.set_item('Title', currItem.get_item('Title'));
aListItem.set_item('Customer', currItem.get_item('Customer'));
aListItem.set_item('Description', currItem.get_item('Description'));
aListItem.set_item('Source', currItem.get_item('Source'));
aListItem.set_item('field2', currItem.get_item('field2'));
aListItem.set_item('field3', currItem.get_item('field3'));
aListItem.set_item('Workloadtype', currItem.get_item('Workloadtype'));
aListItem.set_item('Tickettype', currItem.get_item('Tickettype'));
aListItem.set_item('Customergroup', currEngineer.group);
aListItem.set_item('Allocation', currEngineer.allocation);
aListItem.set_item('SubCap', currItem.get_item('SubCap'));
aListItem.set_item('Engineer', currEngineer.fullName);
aListItem.update();
cc.load(aListItem);
cc.executeQueryAsync(function(){
copyCounter ++;
},function(){
failedCounter ++;
});
}, Function.createDelegate(this,this.getItemFailed));
}
notifyMe();
}
}
In the meantime I found out the resolution (it was good to rethinking the problem for the question).
I fill an array of the required items with the query then processes the array.
var allSelectedItems;
function copySelected(){
if($("#copyAllButton").hasClass('ms-cui-disabled')){
return;
}
var cc = null;
var web = null;
copyCounter = 0;
failedCounter = 0;
cc = new SP.ClientContext.get_current();
web = cc.get_web();
//var currItem = null;
notifyId = SP.UI.Notify.addNotification(duplicatingItemsNotification, true);
var selectedItems;
currList = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList());
selectedItems = SP.ListOperation.Selection.getSelectedItems();
if( selectedItems.length > 0 ){
allSelectedItems = new Array(selectedItems.length);
for(var i in selectedItems){
allSelectedItems[i] = currList.getItemById(selectedItems[i].id);
cc.load(allSelectedItems[i]);
}
cc.executeQueryAsync(Function.createDelegate(this, this.getItemSucceded), Function.createDelegate(this, this.getItemFailed));
notifyMe();
}
}

Categories