Archive for the ‘SharePoint2013’ Category

Introduction
In this article we will explore how to maintain the version of the field and fetch the attachment URL of a list item. Here, I will show how to do it using client side mode via SharePoint Web service using Webservice only ( _vit_bin/lists.asmx)..

Scenario:
The scenario is best suited when in migration from one SharePoint version to another, we need to maintain the attachment URL and the versioning of the fields using Webservice only ( _vit_bin/lists.asmx).
Solutions:
Code:
  1. public static void getListData(string weburl)
  2. {
  3.     Lists.Lists myservice = new Lists.Lists();
  4.     myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
  5.     myservice.Url = weburl + “/_vti_bin/Lists.asmx”;
  6.     try
  7.     {
  8.         /* Assign values to pass the GetListItems method*/
  9.         string listName = “Test List”;
  10.         string viewName = “”;
  11.         string rowLimit = “100”;
  12.         // Instantiate an XmlDocument object
  13.         System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
  14.         System.Xml.XmlElement query = xmlDoc.CreateElement(“Query”);
  15.         System.Xml.XmlElement viewFields = xmlDoc.CreateElement(“ViewFields”);
  16.         System.Xml.XmlElement queryOptions = xmlDoc.CreateElement(“QueryOptions”);
  17.         /*Use CAML query*/
  18.         query.InnerXml = string.Format(“<Where><And>” +
  19.             “<Gt>” +
  20.             “<FieldRef Name=’ID’ /><Value Type=’Counter’>{0}</Value>” +
  21.             “</Gt>” +
  22.             “<Leq><FieldRef Name=’ID’ /><Value Type=’Counter’>{1}</Value></Leq>” +
  23.             “</And></Where>”, 0, 100);
  24.         viewFields.InnerXml = “<FieldRef Name=’Title’ />” +
  25.             “<FieldRef Name=’Created’ />” +
  26.             “<FieldRef Name=’Modified’ />” +
  27.             “<FieldRef Name=’Author’ />” +
  28.             “<FieldRef Name=’Editor’ />”;
  29.         queryOptions.InnerXml = “”;
  30.         System.Xml.XmlNode nodeListItems = myservice.GetListItems(listName, viewName, query, viewFields, rowLimit, nullnull);
  31.         XmlDataDocument xmlDocResult = new XmlDataDocument();
  32.         xmlDocResult.LoadXml(nodeListItems.InnerXml);
  33.         XmlNodeList rows = xmlDocResult.GetElementsByTagName(“z:row”);
  34.         foreach(XmlNode attribute in rows) {
  35.             Console.WriteLine(attribute.Attributes[“ows_Title”].Value);
  36.             string AttachmentUrl = GetAttachmentUrls(weburl, listName, attribute.Attributes[“ows_ID”].Value, “”);
  37.             string vesrsion = GetVersions(weburl, listName, attribute.Attributes[“ows_ID”].Value, “Title”);
  38.         }
  39.     } catch (Exception ex)
  40.     {
  41.         Console.WriteLine(ex.Message);
  42.     }
  43. }
  44. public static string GetAttachmentUrls(string siteUrl, string listId, string itemId, string fieldName)
  45. {
  46.     StringBuilder sb = new StringBuilder();
  47.     Lists.Lists listService = new Lists.Lists();
  48.     listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
  49.     listService.Url = siteUrl + “/_vti_bin/lists.asmx”;#
  50.     region Get the list of attachments
  51.     XmlNode nodeAttachments = listService.GetAttachmentCollection(listId, itemId);
  52.     List < string > values = new List < string > ();
  53.     foreach(System.Xml.XmlNode xNode in nodeAttachments)
  54.     {
  55.         values.Add(xNode.InnerText);
  56.     }
  57.     return string.Join(“;”, values.ToArray());#
  58.     endregion
  59. }
  60. public static string GetVersions(string siteUrl, string listId, string itemId, string fieldName)
  61. {
  62.     StringBuilder sb = new StringBuilder();
  63.     Lists.Lists listService = new Lists.Lists();
  64.     listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
  65.     listService.Url = siteUrl + “/_vti_bin/lists.asmx”;
  66.   #region Get version histories
  67.     if (!string.IsNullOrEmpty(fieldName))
  68.     {
  69.         XmlNode nodeVersions = listService.GetVersionCollection(listId, itemId, fieldName);
  70.         foreach(System.Xml.XmlNode xNode in nodeVersions)
  71.         {
  72.             string dateHistory = xNode.Attributes[“Modified”].Value;
  73.             dateHistory = FormatDateFromSP(dateHistory);
  74.             string commentHistory = xNode.Attributes[fieldName].Value;
  75.             string editor = GetEditor(xNode.Attributes[“Editor”].Value);
  76.             sb.Append(editor + ” (“ + dateHistory + “) “ + commentHistory + “\n\n”);
  77.         }
  78.     }
  79.     return sb.ToString();#
  80.     endregion
  81. }
  82. private static string FormatDateFromSP(string dateHistory)
  83. {
  84.         string result;
  85.         result = dateHistory.Replace(“T”” “);
  86.         result = result.Replace(“Z”“”);
  87.         return result;
  88.     }
  89.     /// <summary>
  90.     /// The XmlNode for version on the Editor contains the Editor Name
  91.     /// </summary>
  92.     /// <param name=”ienumEditor”></param>
  93.     /// <returns></returns>
  94. private static string GetEditor(string nodeValue)
  95. {
  96.     string[] arr;
  97.     char[] sep =
  98.       {
  99.         ‘#’
  100.     };
  101.     // Go for the Editor attribute value
  102.     // A sample is: 30;#Jo�o Faneca,#VIATECLA\\jfaneca,#joao.faneca@viatecla.pt,#joao.faneca@viatecla.pt,#Jo�o Faneca
  103.     arr = nodeValue.Split(sep);
  104.     // Grab the second element for the array
  105.     nodeValue = arr[1];
  106.     // Remove the last comma from the Editor value
  107.     return nodeValue.Remove(nodeValue.Length – 1);
  108. }
  109. }
Summary
Using SharePoint web services to retrieve the version history and attachment URLs for the list item at client side.

CSOM vs JSOM vs SSOM vs REST

Posted: March 12, 2017 in SharePoint2013

Introduction

In this article we will explore different hosting types and technology abbreviations used in SharePoint 2010/2013 and elsewhere too. Useful API reference of the most frequently used types and objects implemented in Server object model (SSOM) and at least one client programming model: .NET client-side object model (CSOM), JavaScript object model (JSOM), and/or REST. Here’s the difference between CSOM/ JSOM/ SSOM/ REST.

image

Model Types

  • CSOM:CSOM core assembly is Microsoft.SharePoint.Client.Runtime.dll and Microsoft.SharePoint.Client.dll, which stands for Client-Side Object Model. It is a web service based API of SharePoint. It allows access to SharePoint data and features from remote clients. CSOM was introduced in SharePoint 2010 and greatly enhanced in SharePoint 2013.SP.ClientContext.get_current() for normal use. New SP.ClientContext(‘url…’) for specific SPWeb.
  • SSOM:Server Object Model core assembly is Microsoft.SharePoint.dll which is installed in the Global Assembly Cache. The Server Object Model will be executed in the server side & it provides rich set of classes in representing & manipulating SharePoint objects. Must be deployed on same farm Server-side object model. C# (or Visual Basic) uses only Microsoft.SharePoint (14) DLL. Must be deployed on same farm.
  • REST:The SharePoint REST interface is based on the REST-based Open Data protocol (OData) which is a platform-independent open standard. REST in 2010 is only for ListData.svc. Note that SPServices (jQuery plugin) utilizes the.asmx services in _/vti/bin , such as /_vti_bin/Webs.asmx.

table

image

Model Types

CSOM:

CSOM, which stands for Client-Side Object Model, is a web services-based API of SharePoint. It allows access to SharePoint data and features from remote clients. CSOM was introduced in SharePoint 2010 and greatly enhanced in SharePoint 2013.

JSOM:

Access information in the host web using the Javascript Object Model, you need to use an SP.ClientContext.get_current() for normal use. New SP.ClientContext(‘url…’) for specific SPSite. Note this works cross-SPSite in 2013.

SSOM:

Server Object Model is the most extensive API set available for SharePoint 2013. The core assembly is Microsoft.SharePoint.dll which is installed in the Global Assembly Cache. The Server Object Model will be executed in the server side & it provides rich set of classes in representing & manipulating SharePoint objects. Must be deployed on same farm.

REST:

The REST Services in SharePoint offer nearly the same functionality like JSOM. Furthermore, it is easier to use for a developer not coming from the SharePoint world since REST interfaces are standardized. This makes the choice of technology easier than for JSOM.

Hosting

SharePoint hosted:

A SharePoint-hosted app may provision basic resources into its app web such as HTML/CSS/JS files, site column/content type/list definitions, etc. Under no circumstances can server-side code run within a SharePoint-hosted app.

Provider hosted:

Provider-hosted apps for SharePoint include components that are deployed and hosted outside the SharePoint farm. They are installed to the host web, but their remote components are hosted on another server, but is meant to be hosted more manually (i.e. On Azure). So you fire up a web application, on any server, and then use S2S to connect to SharePoint.

Sandboxed:

Remnant from 2010, can be uploaded to Solution gallery. Support for limited subset of the SSOM. No file access, so can’t deploy anything to _layouts folder. If you use the limited SSOM-part (C#) your solution will be considered deprecated. Support for templates such as list templates and content types, deployed directly to host web.

Farm solution: Full access, deploy through PowerShell.

table

Note:

Microsoft officially announced the discontinuation of Autohosted apps model in SharePoint Online/Office 365 after it has been tested for the last few months.

Introduction

SharePoint 2013 has greatly expanded the REST services available to developers. With this, we have much more SharePoint functionality exposed via JSOM and Web Services. The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the REST services.

SharePoint REST endpoint Overview:

The following table contains typical REST endpoint URL examples to get you started working with SharePoint data. Prepend http://server/site/_api/ to the URL fragments shown in the table to construct a fully qualified REST URL. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.

URL endpoint Description Supported HTTP Method
/_api/Web/Lists/ getbytitle(‘listname’) Getting a list details by its title and updating it as well. Ifanyone changes your list title, your code will break. GET, POST
/_api/Web/Lists(guid’guid id of your list’) Same as above but changing list title will not affect the code. GET, POST
/_api/Web/Lists/getbytitle(‘ listname ‘)/Fields Retrieving all fields associated with a list and add new fields GET, POST
/_api/Web/Lists/getbytitle(‘listname’)/
Fields/getbytitle(‘fieldname’)
Getting details of a field, modifying and deleting it. GET, PUT, PATCH, MERGE, DELETE
/_api/Web/Lists/getbytitle(‘listname’)/Items Retrieving all items in a list and adding new items GET, POST
/_api/web/lists/getbytitle(‘listname’)
/GetItemById(itemId)
This endpoint can be used to get, update and delete a single item. GET, PUT, PATCH, MERGE, DELETE
/_api/lists/ getbytitle (‘’listname’)/items?$orderby=Title Order Your Results GET, POST
/_api/lists/ getbytitle (‘’listname’)/items?$select=Title,Id Retrieve Selected Column Data value GET, POST
/_api/web/lists/getbytitle(‘listname’)/Items/
?$select=Title,FieldName/Id&$expand= FieldName /Id
Retrieving the lookup value GET, POST

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.

list

Retrieve the list items

item

Here is the main code in detail:

  1. function retriveListItem()
  2. {
  3.     $.ajax
  4.     ({
  5.         url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/GetByTitle(‘companyInfo’)/items?$select=Company,Industry”,
  6.         type: type,
  7.         data: data,
  8.         headers:
  9.         {
  10.             “Accept”“application/json;odata=verbose”,
  11.             “Content-Type”“application/json;odata=verbose”,
  12.             “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
  13.             “IF-MATCH”“*”,
  14.             “X-HTTP-Method”null
  15.         },
  16.         cache: false,
  17.         success: function(data)
  18.         {
  19.             $(“#ResultDiv”).empty();
  20.             for (var i = 0; i < data.d.results.length; i++)
  21.             {
  22.                 var item = data.d.results[i];
  23.                 $(“#ResultDiv”).append(item.Company + “\t” + item.Industry + “<br/>”);
  24.             }
  25.         },
  26.         error: function(data)
  27.         {
  28.             $(“#ResultDiv”).empty().text(data.responseJSON.error);
  29.         }
  30.     });
  31. }

Create list item

create

Here is the main code in detail:

  1. function AddListItem()
  2. {
  3.     var industryVal = $(“#Industry”).val();
  4.     var Company = $(“#Company”).val();
  5.     $.ajax
  6.         ({
  7.         url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/GetByTitle(‘companyInfo’)/items”,
  8.         type: “POST”,
  9.         data: JSON.stringify
  10.         ({
  11.             __metadata:
  12.             {
  13.                 type: “SP.Data.TestListItem”
  14.             },
  15.             Company: Company,
  16.             Industry: industryVal
  17.         }),
  18.         headers:
  19.         {
  20.             “Accept”“application/json;odata=verbose”,
  21.             “Content-Type”“application/json;odata=verbose”,
  22.             “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
  23.             “X-HTTP-Method”“POST”
  24.         },
  25.         success: function(data, status, xhr)
  26.         {
  27.             retriveListItem();
  28.         },
  29.         error: function(xhr, status, error)
  30.         {
  31.             $(“#ResultDiv”).empty().text(data.responseJSON.error);
  32.         }
  33.     });
  34. }

Update list item

update

Here is the main code in detail:

  1. function updateListItem()
  2. {
  3.     var industryVal = $(“#Industry”).val();
  4.     $.ajax
  5.     ({
  6.         url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/GetByTitle(‘companyInfo’)/items(7)”// list item ID
  7.         type: “POST”,
  8.         data: JSON.stringify
  9.         ({
  10.             __metadata:
  11.             {
  12.                 type: “SP.Data.TestListItem”
  13.             },
  14.             Industry: industryVal
  15.         }),
  16.         headers:
  17.         {
  18.             “Accept”“application/json;odata=verbose”,
  19.             “Content-Type”“application/json;odata=verbose”,
  20.             “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
  21.             “IF-MATCH”“*”,
  22.             “X-HTTP-Method”“MERGE”
  23.         },
  24.         success: function(data, status, xhr)
  25.         {
  26.             retriveListItem();
  27.         },
  28.         error: function(xhr, status, error)
  29.         {
  30.             $(“#ResultDiv”).empty().text(data.responseJSON.error);
  31.         }
  32.     });

Delete list item

delete

Here is the main code in detail:

  1. function deleteListItem()
  2. {
  3.     $.ajax
  4.     ({
  5.         url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/GetByTitle(‘companyInfo’)/items(7)”,
  6.         type: “POST”,
  7.         headers:
  8.         {
  9.             “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
  10.             “IF-MATCH”“*”,
  11.             “X-HTTP-Method”“DELETE”
  12.         },
  13.         success: function(data, status, xhr)
  14.         {
  15.             retriveListItem();
  16.         },
  17.         error: function(xhr, status, error)
  18.         {
  19.             $(“#ResultDiv”).empty().text(data.responseJSON.error);
  20.         }
  21.     });
  22. }

Summary

In this article we explored SharePoint 2013 REST API for (CRUD) operations on list items level. I’ve tried to explore crud operation using REST Services, JavaScript Client Side Object Model, and SOAP Services to work on the client side.

Introduction

The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the JSOM. I have explored the CRUD operation using Web Service in my previous article.

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.

SharePoint

Retrieve the list items

Retrieve the list items

Here is the main code in detail:

  1. function retriveListItem()
  2. {
  3.     //Get the current context 
  4.     var context = new SP.ClientContext();
  5.     var list = context.get_web().get_lists().getByTitle(‘companyInfo’);
  6.     var caml = new SP.CamlQuery();
  7.     caml.set_viewXml(“<View><Query><OrderBy><FieldRef Name=’Company’ Ascending=’TRUE’ /></OrderBy></Query></View>”);
  8.     returnedItems = list.getItems(caml);
  9.     context.load(returnedItems);
  10.     context.executeQueryAsync(onSucceededCallback, onFailedCallback);
  11. }
  12. function onSucceededCallback(sender, args)
  13. {
  14.     var enumerator = returnedItems.getEnumerator();
  15.     //Formulate HTML from the list items 
  16.     var MainResult = ‘Items in the Divisions list: <br><br>’;
  17.     //Loop through all the items 
  18.     while (enumerator.moveNext())
  19.     {
  20.         var listItem = enumerator.get_current();
  21.         var companyName = listItem.get_item(“Company “);
  22.                 var Industry = listItem.get_item(“Industry “);
  23.                         MainResult += MainResult + companyName + “-“ + Industry + “\n”;
  24.                     }
  25.                     //Display the formulated HTML in the displayDiv element 
  26.                 displayDiv.innerHTML = MainResult;
  27.             }
  28.             //This function fires when the query fails 
  29.         function onFailedCallback(sender, args)
  30.         {
  31.             //Formulate HTML to display details of the error 
  32.             var markup = ‘<p>The request failed: <br>’;
  33.             markup += ‘Message: ‘ + args.get_message() + ‘<br>’;
  34.             //Display the details 
  35.             displayDiv.innerHTML = markup;
  36.         }
  37.    }
  38. }

Create list item

Create list item

Here is the main code in detail:

  1. function AddListItem()
  2. {
  3.     var listTitle = “companyInfo”;
  4.     //Get the current client context
  5.     context = SP.ClientContext.get_current();
  6.     var airportList = context.get_web().get_lists().getByTitle(listTitle);
  7.     //Create a new record
  8.     var listItemCreationInformation = new SP.ListItemCreationInformation();
  9.     var listItem = airportList.addItem(listItemCreationInformation);
  10.     //Set the values
  11.     Var industryVal = $(“#Industry”).val();
  12.     var Company = $(“#Company”).val();
  13.     listItem.set_item(‘Industry’, +industryVal);
  14.     listItem.set_item(‘Company’, +new item);
  15.     listItem.update();
  16.     context.load(listItem);
  17.     context.executeQueryAsync(AddListItemSucceeded, AddListItemFailed);
  18. }
  19. function AddListItemSucceeded()
  20. {
  21.     retriveListItem();
  22. }
  23. function AddListItemFailed(sender, args)
  24. {
  25.     alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
  26. }

Update list item

Update list item

Here is the main code in detail:

  1. function updateListItem()
  2. {
  3.     var ListName = “companyInfo”;
  4.     var context = new SP.ClientContext.get_current(); // the current context is taken by default here
  5.     //you can also create a particular site context as follows
  6.     var lstObject = context.get_web().get_lists().getByTitle(ListName);
  7.     this.lstObjectItem = lstObject.getItemById(1);
  8.     Var industryVal = $(“#Industry”).val();
  9.     var Company = $(“#Company”).val();
  10.     lstObjectItem.set_item(‘Industry’, “+industryVal + ”);
  11.     lstObjectItem.set_item(‘Company’, ”+Company + ”);
  12.     lstObjectItem.update();
  13.         context.executeQueryAsync(Function.createDelegate(thisthis.onSuccess), Function.createDelegate(thisthis.onFailure));
  14. }
  15. function onSuccess()
  16. {
  17.     retriveListItem();
  18. }
  19. function onFailure(sender, args)
  20. {
  21.     alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
  22. }

Delete list item

Delete list item

Here is the main code in detail:

  1. function deleteListItem()
  2. {
  3.     var listTitle = “companyInfo”;
  4.     //get the current client context
  5.     context = SP.ClientContext.get_current();
  6.     var airportList = context.get_web().get_lists().getByTitle(listTitle);
  7.     //get the list item to delete
  8.     var listItem = airportList.getItemById(1);
  9.     //delete the list item
  10.     listItem.deleteObject();
  11.     context.executeQueryAsync(DeleteItemSucceeded, DeleteItemFailed);
  12. }
  13. function DeleteItemSucceeded()
  14. {
  15.     retriveListItem();
  16. }
  17. function DeleteItemFailed(sender, args)
  18. {
  19.     alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
  20. }

Summary

In this article we explored SharePoint JSOM for CRUD operations on list items level. Hope it will be helpful.

Introduction

In this article we will explore SharePoint functionality via Web Services. The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the SharePoint Web services.

Now, I will demo all the operations on list items including retrieve, create, update and delete on list items.

list items

Retrieve the list items

Retrieve the list items

Here is the main code in detail:
function retriveListItem()
{
var soapEnv = “<soapenv:Envelope xmlns:soapenv=’http://schemas.xmlsoap.org/soap/envelope/’&gt; \
<soapenv:Body> \
<GetListItems xmlns=’http://schemas.microsoft.com/sharepoint/soap/’&gt; \
<listName>companyInfo</listName> \
<viewFields> \
<ViewFields> \
<FieldRef Name=’Company’ /> \
<FieldRef Name=’Industry’ /> \
</ViewFields> \
</viewFields> \
</GetListItems> \
</soapenv:Body> \
</soapenv:Envelope>”;
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + “/apps/_vti_bin/Lists.asmx”,
type: “POST”,
dataType: “xml”,
data: soapEnv,
complete: processResult,
contentType: “text/xml; charset=\”utf-8\””
});
}

function processResult(xData, status)
{
var MainResult = “”;
$(xData.responseXML).find(“z\\:row”).each(function()
{
var companyName = $(this).attr(“ows_Company”);
var Industry = $(this).attr(“ows_Industry”);
MainResult += MainResult + companyName + “-” + Industry + “\n”;
});
$(‘#ResultDiv’).text(MainResult);
}
Create list item

Create list item

Here is the main code in detail:
function createListItem() {
var batch =
“<Batch OnError=\”Continue\”> \
<Method ID=\”1\” Cmd=\”New\”> \
<Field Name=\”Company\”>” + $(“#Company”).val() + “</Field> \
<Field Name=\”Industry\”>” + $(“#Industry”).val() + “</Field> \
</Method> \
ch>”;

var soapEnv =
“<?xml version=\”1.0\” encoding=\”utf-8\”?> \
<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> \
<UpdateListItems xmlns=\”http://schemas.microsoft.com/sharepoint/soap/\”> \
<listName>companyInfo</listName> \
<updates> \
” + batch + “</updates> \
</UpdateListItems> \
</soap:Body> \
</soap:Envelope>”;

$.ajax({
url: _spPageContextInfo.webAbsoluteUrl+ “/apps/_vti_bin/Lists.asmx”,
beforeSend: function(xhr) {
xhr.setRequestHeader(“SOAPAction”,
http://schemas.microsoft.com/sharepoint/soap/UpdateListItems&#8221;);
},
type: “POST”,
dataType: “xml”,
data: soapEnv,
complete: processResult,
contentType: “text/xml; charset=utf-8”
});
}

function processResult(xData, status) {
retriveListItem();
}
Update list item

Update list item

Here is the main code in detail:
function updateListItem() {

var UpdateNewItemXml =
“<Batch OnError=\”Continue\”> \
<Method ID=\”1\” Cmd=\”Update\”> \
<Field Name=\”ID\”>7</Field>\
<Field Name=\”Industry\”>” + $(“#Industry”).val() + “</Field> \
</Method> \</Batch>”;
var soapEnv =
“<?xml version=\”1.0\” encoding=\”utf-8\”?> \
<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> \
<UpdateListItems xmlns=\”http://schemas.microsoft.com/sharepoint/soap/\”> \
<listName>companyInfo</listName> \
<updates> \
” + UpdateNewItemXml + “</updates> \
</UpdateListItems> \
</soap:Body> \
</soap:Envelope>”;

$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + “/apps/_vti_bin/Lists.asmx”,
beforeSend: function (xhr) {
xhr.setRequestHeader(“SOAPAction”,
http://schemas.microsoft.com/sharepoint/soap/UpdateListItems&#8221;);
},
type: “POST”,
dataType: “xml”,
data: soapEnv,
complete: processResult,
contentType: “text/xml; charset=utf-8”
});
}
function processResult(xData, status) {
retriveListItem();
}
Delete list item

Delete list item

Here is the main code in detail:
function deleteListItem()
{
var DeleteItemXml = “<Batch OnError=\”Continue\”> \
<Method ID=\”1\” Cmd=\”Delete\”> \
<Field Name=\”ID\”>7</Field>\
<Field Name=\”Company\”>” + $(“#Company”).val() + “</Field> \
</Method> \</Batch>”;
var soapEnv = “<?xml version=\”1.0\” encoding=\”utf-8\”?> \
<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> \
<UpdateListItems xmlns=\”http://schemas.microsoft.com/sharepoint/soap/\”> \
<listName>companyInfo</listName> \
<updates> \
” + DeleteItemXml + “</updates> \
</UpdateListItems> \
</soap:Body> \
</soap:Envelope>”;
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + “/apps/_vti_bin/Lists.asmx”,
beforeSend: function(xhr)
{
xhr.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/sharepoint/soap/UpdateListItems&#8221;);
},
type: “POST”,
dataType: “xml”,
data: soapEnv,
complete: processResult,
contentType: “text/xml; charset=utf-8”
});
}

function processResult(xData, status)
{
retriveListItem();
}
Summary

In this article we exploreed SharePoint Web service for (CRUD) operations on list items level. Hope it will be helpful.

Introduction

In this article, I will explain the various operations on new, edit and display form using jQuery viz. Hide a field, make read only, set the value at runtime, etc. And I will also explore SPUtility.js,

  • Hidden columns: Introduce these hidden columns on your New and Edit forms but not your Display form as an example. Or what if your scenario requires that they are hidden from all default New, Edit.
  1. Using jQuery

    Before

    listitem

    Step 1: Navigate to your SharePoint 2013 site.

    Step 2: From this page select the Site Actions | Edit Page.

    Edit the page, go to the “Insert” tab in the ribbon and click the “Web Part” option. In the “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 the HTML and/or JavaScript as in the following:

    1. “javascript” src=“/JS/jquery-1.9.0.min.js” type=“text/javascript”>
    2. “javascript” type=“text/javascript”>
    3.     $(document).ready(function() {
    4.         $(‘nobr:contains(“Complete”)’).closest(‘tr’).hide();
    5.         $(‘nobr:contains(“Manager”)’).closest(‘tr’).hide();
    6.     });

    listitem

  2. Using SPUtility.js: SharePoint 2013 using SPUtility.js. SPUtility.js is a powerful js file to work with list or library forms. You can do this by using the SPUtility.js library, As an example I have created a simple list with:

    • Title (simple text).
    • Country (Choice Field) [Tunisia, Switzerland, Canada, France, Other] – Other is the default value.
    • City (Simple text).
    By default the City field is hidden if the Country field value is Other.

    Steps

    Open the list where you want to implement the logic and put the following code inside a script editor web part in the NewForm.aspx. Edit the page, then Add web part and  select a script editor web part.

    1. “text/javascript” src=http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js&#8221;>
    2.     
    3.     “/SiteAssets/Script/sputility.min.js”>
    4.         
    5.         
    6.             // wait for the window to load
    7.             $(document).ready(function()
    8.                 {
    9.                 // Get a single select dropdown field
    10.                 var countryField = SPUtility.GetSPField(‘Country’);
    11.                 // create a function to show or hide City based on Country’s value
    12.                 var showOrHideField = function()
    13.                 {
    14.                     var countryFieldValue = countryField.GetValue();
    15.                     // Hide the City field if the selected value is Other
    16.                     if (countryFieldValue === ‘Other’)
    17.                     {
    18.                         SPUtility.HideSPField(‘City’);
    19.                     } else {
    20.                         SPUtility.ShowSPField(‘City’);
    21.                     }
    22.                 };
    23.                 // run at startup (for edit form)
    24.                 showOrHideField();
    25.                 // make sure if the user changes the value we handle it
    26.                 $(countryField.Dropdown).on(‘change’, showOrHideField);
    27.             });
    28.         

    The result

    result

    Disabled or read-only

    Text Field: Disabled or read-only to multiple lines of text field and single line text in Edit form in SharePoint list.

    Before

    edit

    Steps

    Open the list where you want to implement the logic and put the following code inside a script editor web part in the NewForm.aspx . Edit the page – Add web part and then select a script editor web part.

    1. “javascript”src=“/JSLibrary/jquery-1.9.0.min.js”type=“text/javascript”>
    2. “javascript”type=“text/javascript”>
    3. $(document).ready(function ()
    4. {
    5.     ConvertTextboxToLable(‘Title’);
    6.     ConvertTextareaToLable(‘Description’);
    7. });
    8. //Convert Multiline Text Area to Lable
    9. function ConvertTextareaToLable(colName)
    10. {
    11.     var txtHTML = $(“textarea[Title='” + colName + “‘]”).html();
    12.     var tdColumn = $(“textarea[Title='” + colName + “‘]”).closest(‘td’);
    13.     var tdColumnHTML = $(tdColumn).html();
    14.     $(tdColumn).html(
      ‘” + tdColumnHTML + “‘

      “);

    15.     $(tdColumn).append(txtHTML);
    16. }
    17. //Convert Single Line Textbox to Lable
    18. function ConvertTextboxToLable(colName)
    19. {
    20.     var txtHTML = $(“input[type=text][Title='” + colName + “‘]”).val();
    21.     var tdColumn = $(“input[type=text][Title='” + colName +
    22.     “‘]”).closest(‘td’);
    23.     var tdColumnHTML = $(tdColumn).html();
    24.     $(tdColumn).html(
      ‘” + tdColumnHTML +
    25.     “‘

    “);

  3.     $(tdColumn).append(txtHTML);
  4. }

Result

edit

People Picker Field

Disable People Picker / Lookup fields in SharePoint list forms (EditForm.aspx).

Before

edit

Steps

Open the list where you want to implement the logic and put the following code inside a script editor web part in the NewForm.aspx (Edit the page, then Add web part and select a script editor web part.

  1. “javascript”src=“/JSLibrary/jquery-1.9.0.min.js”type=“text/javascript”>
  2. “javascript”type=“text/javascript”>
  3. $(document).ready(function ()
  4. {
  5.     var control = $(“textarea[title=’People Picker’]”)[0];
  6.     /* Detect browser*/
  7.     if (navigator.appName == ‘Microsoft Internet Explorer’)
  8.         {
  9.             control.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.childNodes[1].style.display = “none”;
  10.         }
  11.         else
  12.         {
  13.             control.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.childNodes[2].style.display = “none”;
  14.         }
  15.         var innerHtml = control.parentNode.parentNode.innerHTML;
  16.     control.parentNode.style.display = “none”;
  17.     control.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML = control.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML +  + $(‘.ms-inputuserfield #content’).text() + ;
  18. });

Result

edit

Adding a title on form:A custom title can be added on the list form on runtime using jQuery.

Before

title
Steps

Open the list where you want to implement the logic and put the following code inside a script editor web part in the NewForm.aspx. Edit the page, Add web part and then select a script editor web part.

  1. “javascript” src=“/JSLibrary/jquery-1.9.0.min.js” type=“text/javascript”>
  2.     
  3.     “javascript” type=“text/javascript”>
  4.         $(document).ready(function ()
  5.        {
  6.       var table = $(‘table.ms-formtable’); // Add a row with the ID in table.prepend(“
  7.         
  8.              class=‘ms-formlabel’>
  9.                 

    class=‘ms-standardheader’>Employee Details

    ” + “

  10.              class=‘ms-formbody’>
  11.         

    “); });

  12.      

Result:

result

Introduction
In this article you will learn about the Rich TextBox validation using JQuery in SharePoint 2013.

I observed that the mandatory enhanced/rich text box of SharePoint 2013 doesn’t throw an error when we cut the content from it from the edit/new form and it allows us to save the form without any content in rich text box. The article describes the steps to remove this error.

error

Scenario

On the new/edit form we have enhanced/rich text which is a mandatory field. If we edit the rich text box and cut the content present inside it, the validation doesn’t work. The issue has been resolved.

Solution

Need to avoid the div tags and get data alone from multiline textbox field using the following script,

Step 1: Navigate to your SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “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 the HTML and/or JavaScript as in the following:

  1. “text/javascript”>
  2.     $(document).ready(function()
  3.     {
  4.         var reg1 = new RegExp(
    [^, “”);
  5.         var reg2 = new RegExp(

$”, “”);

  •         var Fieldname = $(“td.ms-formlabel h3.ms-standardheader nobr:contains(‘Field Name’)”).parent().parent().parent().find(“div.ms-inputBox div.ms-rtestate-write”).html().replace(reg1, “”).replace(reg2, “”);
  •         var contenttext = $(“td.ms-formlabel h3.ms-standardheader nobr:contains(‘Field Name’)”).parent().parent().parent().find(“div.ms-inputBox div.ms-rtestate-write”).text();
  •         if (contenttext == “”)
  •         {
  •             $(“td.ms-formlabel h3.ms-standardheader nobr:contains(‘Field Name’)”).parent().parent().parent().find(“div.ms-inputBox div.ms-rtestate-write”).html(Fieldname);
  •         }
  •     });
  •