Archive for September, 2019

Introduction

In my previous blog, I explored _spPageContextInfo variable properties. This time, I am exploring some SharePoint-provided useful methods and objects in JavaScript. Following are the methods and objects which I use frequently in JavaScript. All these are available Out-Of-The-Box and you don’t need to add any JavaScript library.

JSRequest (Object)
This is used for getting Query String Values. JSRequest class is a JavaScript object in SharePoint. Before using any of these properties, you should call JSRequest.EnsureSetup();

Ex: page URL is http://Siteur/ListName/EditForm.aspx?ID=9

To get a query string value, use the following code.

  1. JSRequest.EnsureSetup();
  2. var Id = JSRequest.QueryString[“ID”]; // Id= 8

Similarly, you can use this –

  1. JSRequest.EnsureSetup();
  2. var fileName = JSRequest.FileName; // current page name
  3. var pathname = JSRequest.PathName; // server relative url

GetUrlKeyValue(parameter, noDecode, url) (Method)
These SharePoint utilities and functions are available on the client-side of SharePoint 2013 to get the value from the query string of the URL.

  1. alert(GetUrlKeyValue(‘a’false‘www.xyz.com?a=fi%20rst’));  

The above statement will return the value ‘fi rst’. Here we are specifying our own URL.

  1. alert(GetUrlKeyValue(‘S’false));  

The above statement will look for a query string variable ‘S’ in the browser URL and return the decoded value.

  1. alert(GetUrlKeyValue(‘S’));  

The above statement will look for a query string variable ‘S’ in the browser URL.

SetUrlKeyValue (parameterName, parameterValue, bEncode, url)
This SharePoint utility is opposite to GetUrlKeyValue. In GetUrlKeyValue function, we will get the value from the query string and in SetUrlKeyValue, we will be setting the value to the query string .

  • parameterName
    The query string name to which we need to set the value.
  • parameterValue
    The parameter value that needs to be set to the keyName.
  • bEncode
    Whether the value needs to be encoded in the URL before setting the value.
  • url
    Url to which the value needs to be set.

    1. SetUrlKeyValue(‘EditPage’‘true’false, window.location.href);  
    2. SetUrlKeyValue(‘EditPage’‘true’false,http://www.google.com’);     
  • ScriptUtility
    This class is the home to six very useful helper methods and one helper field.
  • emptyString
    This field returned an empty string in JavaScript “ ”

SP.ScriptUtility Methods

  • isNullOrEmptyString – Checks if the specified text is null, an empty string or undefined
  • isNullOrUndefined – Checks if the specified object is null or undefined.
  • isUndefined – Checks if the specified object is undefined.
  • truncateToInt – Returns largest integer value that is less than or equal to the specified number if the number is greater than 0 else returns the smallest integer value that is greater than or equal to the number.
  • ScriptUtility : It merely acts as a placeholder for the class name SP.ScriptUtility to hold the Above methods.

escapeProperly(str) (Method)

This function returns escapeProperly function returns the encoded value for provided string.

  1. var s = escapeProperly(“hello world!!”); //s = “hello%20world%21%21”  

SP.Guid

The function SP.Guid.newGuid().toString() returns new GUID at runtime.

  1. var  guid=SP.Guid.newGuid().toString();//guid =”260868ac-2c0c-4494-a40e-22b00aaa0312″  

unescapeProperly(str) (Method)

This function returns unescapeProperly function that returns decoded string for provided encoded string.

  1. var Outstr=unescapeProperly(“this%20is%20a%20test”)//Outstr=”this is a test”  

escapeProperly(str) (Method)

This function returns escapeProperly function returns the encoded value for provided string.

  • Location
  • init.js
  • Parameters
  • str
    1. var urlEncodedValue = escapeProperly(“My Value”); // Returns “My%20Value”.  

TrimSpaces(str)

This function can be to trim spaces on a string. A string that will be trimmed. Return value he trimmed string.

  1. var trimmed = TrimSpaces(” string with spaces “); // Returns “string with spaces”.  

TrimWhiteSpaces(str)

This method trims the white spaces of a string and It also removes spaces created spaces, tabs and linebreaks (\t \n \r \f). A string that will be trimmed.Return valueThe trimmed string.

  1. var trimmed = TrimWhiteSpaces(“\t\tstring with spaces\n”);  // Returns “string with spaces”.  

variable :L_Menu_BaseUrl

This variable contains the base URL of the current site or subsite.

Ex. document.location = L_Menu_BaseUrl + ‘Lists/Tasks/AllItems.aspx’;
variable: L_Menu_LCID

This variable contains the LCID setting of the current site.
Variable: L_Menu_SiteTheme

This variable contains the theme name of the current site.
Lots of this JavaScript Function is already written for you in SharePoint’s “Init.js“and “core.js” file follow the below tables,

Init.js (Function)
  • ULSTrim(str)
  • ULSEncodeXML(str)
  • PageUrlValidation(url)j GetCurrentEltStyle(element, cssStyle)
  • IsCheckBoxListSelected(checkboxlist)
  • STSHtmlEncode(str)
  • DeleteCookie(sName)
  • GetCookie(sName)
  • navigateMailToLink(strBody)
  • navigateMailToLinkWithMessage(strTo, strBody)
  • makeAbsUrl(strUrl)
  • HideMenuControl(menuControlId)
  • displayPNGImage(id,src,width,height,alt)
  • GetUrlKeyValue(keyName, bNoDecode, url)
  • GoToPage(url)
  • TrimSpaces( str )
  • TrimWhiteSpaces( str )
  • FormatDate(sDate, sTime, eDate, eTime)
  • GetElementByClassName(elem, classname)
  • WpClick(evt)
  • GetViewportHeight()
  • GetViewportWidth()
  • RemoveQueryParameterFromUrl(stURL, stParameterName)
  • HasValidUrlPrefix(url)
  • AbsLeft(obj)
  • AbsTop(obj)
  • ExecuteOrDelayUntilScriptLoaded(func, depScriptFileName)
  • ShowPopupDialog(dlgUrl)
core.js(Function)
  • NewItem(url)
  • EditItem(url)
  • RefreshPageTo(evt, url, bForceSubmit)
  • PopMenuFromChevron(e)
  • RefreshPage(dialogResult)
  • OpenPopUpPage(url, callback, width, height)
  • OnIframeLoad()
  • RemoveUrlKeyValue(keyName, url)
  • RemoveParametersFromUrl(url)
  • _GoToPageRelative(url)
  • ShowInPopUI(evt, currentCtx, strUrl)
  • OpenPopUpPageWithTitle(url, callback, width, height,title)
  • AddSourceToUrl(url)
  • ConvertMultiColumnValueToString(subColumnValues,delimiter,bAddLeadingTailingDelimiter)
  • Log(str)
  • CountTotalItems(ctxCur)
  • CountSelectedItems(ctxCur)
  • _addNotificationInternal(span, strHtml, bSticky, tooltip, onclickHandler, bNoAnimate)
  • removeNotification(id, bNoAnimate)
  • SetCookie(name, value, path)

Introduction

In this article, we will explore in Sharepoint 2013, how to show the Sharepoint list item level attachments using REST API and jQuery.  In the previous article, I explained about adding multiple attachments to list item using HTML and jQuery. Now, let’s use some REST API to pull these attachments and display them in the list.

For retrieving attachments, I am using REST API. The URL for all attachment collections can be built like below.

{Site URL}/_api/web/lists/getbytitle([List Title])/items([item ID])/AttachmentFiles

Scenario

I have created a custom list on the host site named “Attachment”. Add multiple items with attachments and let’s say that we want to show the item level attachments in the item selection.

SharePoint

I have an item (Item ID: 1) that has the following attachments
SharePoint

Objective

I wanted to get the URLs of the list item attachments so that I could use it in my HTML and to fetch the Item ID of the list item and bind to the drop-down. Once we have selected any Item ID from the list of Item IDs from the drop-down, the attachments of the respective item are shown. An “on change” event is used to fetch and we show the related attachments.

Use the procedure given below.

Step 1

Navigate to your SharePoint 2013 site.

Step 2

From this page, select Site Actions | Edit Page.

Edit the page, go to the Insert tab in the Ribbon and click Web Part option. In Web Parts picker area, go to the “Media and Content” category, select the Script Editor Web Part and press the “Add” button.

Step 3

Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

  1. “text/javascript” src=“../../SiteAssets/Script/jquery-1.9.1.min.js”>
  2.     “text/javascript”>
  3.         $(document).ready(function ($) {
  4.             var url = _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/getbytitle(‘Attachments’)/items?$select=Id”;
  5.             getListItems(url, function (data) {
  6.                 var items = data.d.results;
  7.                 var SelectElement = ‘Select’;
  8.                 // Add all the Item Id in Dropdown
  9.                 for (var i = 0; i
  10.                     var itemId = items[i].Id;
  11.                     SelectElement += ‘ + itemId + ‘”selected>’ + itemId + ;
  12.                 }
  13.                 SelectElement += ;
  14.                 $(‘#ItemID’).append(SelectElement);
  15.                 // assign the change event 
  16.                 $(‘#drpListItem’).on(‘change’function () {
  17.                     if ($(this).val() != “”) {
  18.                         var Requestorurl = _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/getbytitle(‘Attachments’)/items(“ + $(this).val() + “)/AttachmentFiles”;
  19.                         getListItems(Requestorurl, function (data) {
  20.                             var results = data.d.results;
  21.                             var htmlStr = “”;
  22.                             if (data.d.results.length > 0) {
  23.                                 $.each(data.d.results, function () {
  24.                                     if (htmlStr === “”) {
  25.                                         htmlStr = 
  26.  + this.ServerRelativeUrl + “‘>” + this.FileName + 
  27. “;
  28.                                     }
  29.                                     else {
  30.                                         htmlStr = htmlStr + 
  31.  + this.ServerRelativeUrl + “‘>” + this.FileName + 
  32. “;
  33.                                     }
  34.                                 });
  35.                             }
  36.                             else { htmlStr = There are no attachments to show in this item.; }
  37.                             $(‘#attachmentsContainer’).html(htmlStr);
  38.                         });
  39.                     }
  40.                 });
  41.             }, function (data) {
  42.                 console.log(“An error occurred. Please try again.”);
  43.             });
  44.         });
  45.         function getListItems(siteurl, success, failure) {
  46.             $.ajax({
  47.                 url: siteurl,
  48.                 method: “GET”,
  49.                 headers: { “Accept”“application/json; odata=verbose” },
  50.                 success: function (data) {
  51.                     success(data);
  52.                 },
  53.                 error: function (data) {
  54.                     failure(data);
  55.                 }
  56.             });
  57.         }

Final Output

  1. List Item with attachments.SharePoint
  2. List item without attachments.SharePoint