Custom Client Side People Picker in SharePoint using jQuery

Hello friends, in this tutorial we will develop a custom client side people picker control in SharePoint. It is applicable for SharePoint 2013, 2016 and SharePoint Online.

In the first section, we will save the people picker value in SharePoint list (people picker field) using REST API.

In the second section we will see, how to get the value of people picker field from SharePoint list and set to our custom people picker field, as shown below:

Section 1: Create custom people picker field and save its value in SharePoint list.

Step 1: Create a list named EmpDetails. Create a person or group field named EmployeeName. We are going to save of custom field value in this list field.

Step 2: Create a webpart page and add content editor webpart

Step 3: Add below code and we are ready with our custom field.

Download below code: Download link

<!-- Created by https://myclassbook.org/custom-client-side-people-picker-in-sharepoint-using-jquery/ -->
<html>
   <head>
      <script src="/teams/MyClassBook/CustomCode/jquery.min.js"></script> 
      <script src="/_layouts/15/sp.runtime.js"></script>  
      <script src="/_layouts/15/sp.js"></script>  
      <script src="/_layouts/15/1033/strings.js"></script>  
      <script src="/_layouts/15/clienttemplates.js"></script>  
      <script src="/_layouts/15/clientforms.js"></script>  
      <script src="/_layouts/15/clientpeoplepicker.js"></script>  
      <script src="/_layouts/15/autofill.js"></script>  
      <script src="_layouts/15/sp.core.js"></script> 
      <script>
         // Run your custom code when the DOM is ready.
         $(document).ready(function () {
         
             // Specify the unique ID of the DOM element where the
             // picker will render.
             initializePeoplePicker('peoplePickerDiv');
         });
         
         // Render and initialize the client-side People Picker.
         function initializePeoplePicker(peoplePickerElementId) {
         
             // Create a schema to store picker properties, and set the properties.
             var schema = {};
             schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
             schema['SearchPrincipalSource'] = 15;
             schema['ResolvePrincipalSource'] = 15;
             schema['AllowMultipleValues'] = true;
             schema['MaximumEntitySuggestions'] = 50;
             schema['Width'] = '280px';
         
             // Render and initialize the picker. 
             // Pass the ID of the DOM element that contains the picker, an array of initial
             // PickerEntity objects to set the picker value, and a schema that defines
             // picker properties.
             this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
         }
         
         // Query the picker for user information.
         function getUserInfo() {
         
             // Get the people picker object from the page.
             var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
         
             // Get information about all users.
             var users = peoplePicker.GetAllUserInfo();
             var userInfo = '';
             for (var i = 0; i < users.length; i++) {
                 var user = users[i];
                 for (var userProperty in user) { 
                     userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
                 }
             }
             $('#resolvedUsers').html(userInfo);
         
             // Get user keys.
             var keys = peoplePicker.GetAllUserKeys();
             $('#userKeys').html(keys);
         
             // Get the first user's ID by using the login name.
             getUserId(users[0].Key);
         }
         
         // Get the user ID.
         function getUserId(loginName) {
             var context = new SP.ClientContext.get_current();
             this.user = context.get_web().ensureUser(loginName);
             context.load(this.user);
             context.executeQueryAsync(
                  Function.createDelegate(null, ensureUserSuccess), 
                  Function.createDelegate(null, onFail)
             );
         }
         
         function ensureUserSuccess() {
         	createitem(this.user.get_id());
             $('#userId').html(this.user.get_id());
         }
         
         function onFail(sender, args) {
             alert('Query failed. Error: ' + args.get_message());
         }   
         
         //Rest API function to create an item in a list
         function createitem(userId){
         	$.ajax({
                 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmpDetails')/Items",
                 type: 'POST',
                 headers: {
                     "Accept": "application/json;odata=verbose",
                     "Content-Type": "application/json;odata=verbose",
                     "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                     "X-HTTP-Method": "POST"
                 },
                 data: JSON.stringify({
                     __metadata: {
                         type: "SP.Data.EmpDetailsListItem"
                     },
                     Title: "Mayuresh Dinkar Joshi",            
                     EmployeeNameId: userId, //internalName is 'EmployeeName' but we have to use 'EmployeeNameId' to pass id of a person            
                 }),
                 success: function(data) {
                     alert('Item created successfully!');
                 },
                 error: function(error) {
                     alert(JSON.stringify(error));
                 }
             });
         }   
      </script>
   </head>
   <body>
      <div id="peoplePickerDiv"></div>
      <div>
         <br/>
         <input type="button" value="Get User Info and Create Item" onclick="getUserInfo()"></input>
         <br/>
         <h1>User info:</h1>
         <p id="resolvedUsers"></p>
         <h1>User keys:</h1>
         <p id="userKeys"></p>
         <h1>User ID:</h1>
         <p id="userId"></p>
      </div>
   </body>
</html>

Step 4: Our custom people picker field will look like as below:

Custom people picker field

Step 5: When we search for any name and click on button, it will populate that users details and also save the value in our custom list field which we created in step 1. See below screenshots:

Custom people picker field in sharepoint
Custom people picker field in SharePoint
Custom people picker field in SharePoint
Custom people picker field in SharePoint

Section 2: Get person field value from SharePoint list and set the value to custom people picker field.

Step 1: We have a list named EmpDetails with person or group field as EmployeeName.

Step 2: We will fetch the value for an item with ID=1 and set its value to our custom people picker field.

Step 3: Create a webpart page and add content editor webpart.

Step 4: Add below code in content editor webpart.

Note: I have passed hard-coded URL with item ID 1. I will recommend you to edit the logic accordingly to pass the ID dynamically using text field.

Download below code: Download link

<!--Created by https://myclassbook.org/custom-client-side-people-picker-in-sharepoint-using-jquery/ -->
<html>
<head>
    <script src="/teams/MyClassBook/CustomCode/jquery.min.js"></script>
    <script src="/_layouts/15/sp.runtime.js"></script>
    <script src="/_layouts/15/sp.js"></script>
    <script src="/_layouts/15/1033/strings.js"></script>
    <script src="/_layouts/15/clienttemplates.js"></script>
    <script src="/_layouts/15/clientforms.js"></script>
    <script src="/_layouts/15/clientpeoplepicker.js"></script>
    <script src="/_layouts/15/autofill.js"></script>
    <script src="_layouts/15/sp.core.js"></script>
    <script>
        // Run your custom code when the DOM is ready.
        $(document).ready(function() {
            // Specify the unique ID of the DOM element where the
            // picker will render.
            initializePeoplePicker('peoplePickerDiv');
        });
        // Render and initialize the client-side People Picker.
        function initializePeoplePicker(peoplePickerElementId) {
            // Create a schema to store picker properties, and set the properties.
            var schema = {};
            schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
            schema['SearchPrincipalSource'] = 15;
            schema['ResolvePrincipalSource'] = 15;
            schema['AllowMultipleValues'] = true;
            schema['MaximumEntitySuggestions'] = 50;
            schema['Width'] = '280px';
            // Render and initialize the picker. 
            // Pass the ID of the DOM element that contains the picker, an array of initial
            // PickerEntity objects to set the picker value, and a schema that defines
            // picker properties.
            this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
        }
        function readItem() {
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmpDetails')/Items(1)?$select=EmployeeName/EMail&$expand=EmployeeName/Id",
                type: 'GET',
                headers: {
                    "accept": "application/json;odata=verbose",
                },
                success: function(data) {
                    console.log(data.d.EmployeeName.EMail);
                    SetAndResolvePeoplePicker(data.d.EmployeeName.EMail);
                },
                error: function(error) {
                    alert(JSON.stringify(error));
                }
            });
        }
        function SetAndResolvePeoplePicker(userAccountName) {
            var _PeoplePickerEditer = $("#peoplePickerDiv_TopSpan_EditorInput");
            userAccountName.split(";#").forEach(function(part) {
                if (part !== "" && part !== null) {
                    //  alert(part);
                    _PeoplePickerEditer.val(part);
                    var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict["peoplePickerDiv_TopSpan"];
                    _PeoplePickerOject.AddUnresolvedUserFromEditor(true);
                }
            });
        }
    </script>
</head>
<body>
    <div id="peoplePickerDiv"></div>
    <div>
        <br />
        <input type="button" value="Set people picker" onclick="readItem()"></input>
        <br />
    </div>
</body>
</html>

Step 5: When we click on a given button, it will call a REST API to fetch the value of person field of list item of ID 1 and set its value to out custom people picker field. We can use this scenario when we need to fetch person fields in our custom edit form.

I hope you liked this article. If you have any queries, please use below comments section for the same. Please like our facebook page and subscribe to our newsletter for future updates. Have a nice day! tada…

How to Hide SharePoint Field using jQuery/JavaScript

Hello friends, in this article, we will see how we can Hide SharePoint Field in NewForm.aspx/ DispForm.aspx/ EditForm.aspx

Add a content editor webpart on respective pages (NewForm.aspx/ DispForm.aspx/ EditForm.aspx) and use below JavaScript/jQuery code to hide sharepoint field. In this case, I am hiding named “Middle Name”.

  1. For NewForm.aspx OR EditForm.aspx

    using jQuery

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $('nobr:contains("Middle Name")').closest('tr').hide(); //here we are hiding field named "Middle Name"
    });
    </script>

    using JavaScript

    <script type="text/javascript">
    
    // The new closest
    var closest = function(el, fn) {
      return el && (fn(el) ? el : closest(el.parentNode, fn));
    };
    
    // Get the "starting point" element
    var srcEl = document.getElementById('Middle_x0020_Name');
    
    // `<tr>` is the "ending point"
    var tr = closest(srcEl, function(el) {    
        return el.tagName.toLowerCase() === 'tr';
    });
    
    tr.style.display = "none";
    
    </script>
    
    
  2. For DispForm.aspx

    using jQuery

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $('[name="SPBookmark_Middle_x0020_Name"]').closest('tr').hide();
    });
    </script>

    using JavaScript

    <script type="text/javascript">
    
    // The new closest
    var closest = function(el, fn) {
      return el && (fn(el) ? el : closest(el.parentNode, fn));
    };
    
    // Get the "starting point" element
    var srcEl = document.getElementsByName('SPBookmark_Middle_x0020_Name');
    srcEl;
    // `<tr>` is the "ending point"
    var tr = closest(srcEl[0], function(el) {    
        return el.tagName.toLowerCase() === 'tr';
    });
    
    tr.style.display = "none";
    
    </script>

Explanation of code:

How to hide SharePoint field using JavaScript

If you see the first code for hiding SharePoint field on New or Edit forms, we have used the closest function of jquery. We are using <nobr> tag value to find the closest <tr> tag of the field and hiding it. You can refer below screenshot to find the <nobr> value (It’s always same as field display name).

Hide SharePoint Field
Hide SharePoint Field

A similar approach is used for remaining codes. I hope you have liked this article. If you have any queries, feel free to ask in the comment section below. Like our facebook page and subscribe to our newsletter for future updates. Have a nice day!

Recommended articles:

  1. SharePoint Interview Questions
  2. SharePoint Content Types – Best Explained
  3. SharePoint Site Columns – Best Explained
  4. How to Make Conditionally Mandatory Field in SharePoint 2013

Add Geolocation column in SharePoint using PowerShell

Hello Friends, in this article we will learn  how to add Geolocation column in SharePoint. Using powershell, we can enable a Geo-location column on a custom list in SharePoint online. We will use a PowerShell script to add Geo-location column in our list. The same script can be used for SharePoint 2010/2013.

Add Geolocation column in SharePoint using PowerShell

  1. Open Windows PowerShell ISE

    Windows PowerShell ISE
    Windows PowerShell ISE
  2. Write below PowerShell code and run the same. Make the necessary changes in the below code like: $WebUrl, $EmailAddress, $List.
    #Load SharePoint CSOM Assemblies
    Add-Type -Path "C:\Users\Desktop\Data\Old\Microsoft.SharePoint.Client.Runtime.dll"
    Add-Type -Path "C:\Users\Desktop\Data\Old\Microsoft.SharePoint.Client.dll"
    
    #Define SharePoint URL, login details
    $WebUrl = 'https://myclassbook.sharepoint.com/teams/TestSite/'
    $EmailAddress = "[email protected]"
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
    $Credentials = Get-Credential -UserName $EmailAddress -Message "Please enter your Office 365 Password"
    $Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($EmailAddress,$Credentials.Password)
    
    #Define list name where we need to add Geolocation column
    $List = $Context.Web.Lists.GetByTitle("Project Portals")
    $FieldXml = "<Field Type='Geolocation' DisplayName='Location'/>"
    $Option=[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView
    $List.Fields.AddFieldAsXml($fieldxml,$true,$option)
    $Context.Load($list)
    $Context.ExecuteQuery()
    $Context.Dispose()

    Screenshot of the above code:

    Add geolocation column in sharepoint using powershell
    Add Geo-location column in SharePoint using PowerShell
  3. Once the script is successfully executed, you can see that the Geolocation columns with Display Name “Location” will be added in your list.

    Add Geolocation column in SharePoint using PowerShell
    Add Geolocation column in SharePoint using PowerShell

Downloads:
1) Microsoft.SharePoint.Client.Runtime.dll
2) Microsoft.SharePoint.Client.dll
3) PowerShell Script

You may also like:

I hope you liked this article. Please let us know in case you are having any questions in the comment section below. Like our facebook page and subscribe to our newsletter for future updates. have a great time 🙂

Export all users from SharePoint group in Excel

Hello friends, in this article we will see how we can export a list of all users present in a SharePoint group.

Export all users from SharePoint group in Excel

  1. Open Microsoft Excel and Click on From OData Data Feed as shown below:

    Click on
    Click on “From OData Data Feed”
  2. In ‘Data Connection Wizard’ Enter the REST URL as below:

    https://myclassbook.sharepoint.com/teams/TestSite/_api/Web/SiteGroups/getbyid(142)/UsersMake sure that you have entered the correct site URL and group ID. You can find the group ID by opening specific group URL: 

  3. Click on Next and you will ask to choose the required Data. In this case we will only get the option for Users. Check it and click on Next.
  4. You can then see that the data will be loading in your Excel:
  5. Once it retrieves all the users from SharePoint group, you can save the file 🙂

I hope you liked this article. Please let us know in case you are having any questions in the comment section below. Like our facebook page and subscribe to our newsletter for future updates. have a great time 🙂

SharePoint Content Types – Best Explained

Hello folks, in this article I will try to explain SharePoint Content types in details. Most of the SharePoint beginners find it difficult to understand what exactly the content type is? and how we can use it in SharePoint? We will try to learn SharePoint content types by comparing it with one day-to-day example. We will cover the advantages and use of SharePoint content types during this course as well.

Day-to-day example (to understand SharePoint content types)

The example that we are going to discuss is the Banking system. When we need to make some transactions like cash withdrawal, cash deposit, cheque encashment, etc. we use different formats of slips. Making use of different format slips for different purposes makes it easy for bank officers to differentiate the type of transaction.

Consider that the bank has one big box in which they keep all kind of slips together. By the end of the day, it will be easier for them to differentiate the different formats of slips and make the calculations. If they would have used the same slip format for all kind of transactions (deposit, withdrawal, etc) it would have become difficult for them to deal with them. It may cause the huge loss for the bank as well.

SharePoint Content Types

In this example, you can consider

  • Big box (in which the slips are collected) as your list or library
  • Different formats of slips as SharePoint Content Type
  • Unique fields (like Name, Account number, Signature) in all formats of slips as Site columns

Thus, a content type is a reusable group of site columns which represents a set of information.

You can find another awesome example given by Greg here: Content Types Example

SharePoint Content Types

You will hear the word Content type every day while working with SharePoint. It is very important to understand and utilize the same. According to Microsoft, A content type is a reusable collection of metadata (columns), workflow, behavior, and other settings for a category of items or documents in a SharePoint list or document library. Content types enable you to manage the settings for a category of information in a centralized, reusable way.

SharePoint content type provides one more advantage to you, whenever you make any changes in content type, it provides an option whether to apply the new changes to all the lists (which are using that particular content type) or not.

If you have worked on a Task list or Announcement list then you have already used a content type. SharePoint has many default content types. If you create a new Task list, you can see that there are some columns already available like Task name, start date, due date, etc. These columns are default site columns and the Task list is using default content type as Task as shown below.

SharePoint Content Types

How to create a SharePoint content type?

Before creating a Content type you should make note of below important points

  1. It’s a best practice to create a Content type under the root site (top site) so that it can be used under all subsites as well. This is again based on the requirements of the organization because users don’t want to have too many content types under the root sites, which are not useful.
  2. If you create a Content type in a subsite, you cant use that Content type in your root site.
  3. When you update the Content type, it’s your wish whether to apply the updates on existing lists or not.
  4. If you want to delete the content type from the site collection, you need to remove that content type from all the associated list/libraries.

A) Create a content type for List

  1. Create a list named BankingSystem
  2. We will create 2 content types named Cash Deposit and Cash Withdrawal 
  3. Create 3 site columns named Customer Name, Account Number, Signature (You can read this article on creating site columns: SharePoint Site Columns)
  4. Go to Site Settings> Web Designer Galleries > Site content types
    SharePoint Content Types
  5. Click on create
  6. Enter the information as shown below. It will ask you to choose a Parent Content type, you can choose anyone. In this case, I have chosen Item content type. Item content type by default has Title site column only. Finally, click on OK
    SharePoint Content Types
  7. Now our content type is ready but before using it we have to first add site columns to it.
  8. To add site columns to this content type, go to Site SettingsWeb Designer Galleries > Site content types > Click on newly created a content type (Cash Deposit)
  9. Click on Add from existing site columns
    SharePoint Content Types
    10. Add the site columns to this content type. Here is an important point need to be noted. Add all the required site columns for this content type. In the below screenshot I have added only 3 but you can add as many as you want to make it different from other content types.
    SharePoint Content Types
  10. Similarly, add another content type and name it Cash Withdrawal with some different site columns.
  11. Now both the content types are ready for use. Let’s add these content types to a List named BankingSystem
  12. Go to List Settings > Advanced settings > make sure the Allow management of content type is selected as shown below:
    SharePoint Content Types
  13. Click on Add from existing site content types
  14. Add both the custom content types as shown below
  15. You can see both these content types are available under the New Item option

B) Create a SharePoint Content Type for Document Library

  1. Create a Document Library named BankingSystem
  2. We will create 2 content types named Cash Deposit and Cash Withdrawal 
  3. Create 3 site columns named Customer Name, Account Number, Signature (You can read this article on creating site columns: SharePoint Site Columns)
  4. Go to Site Settings > Web Designer Galleries > Site content types
  5. Then click on create.
  6. Enter the information as shown below. It will ask you to choose a Parent Content type, you can choose anything. In this case, I have chosen Document content type. Finally, click on OK
    SharePoint Content Types
  7. Now our content type is ready but before using it we can add site columns to it or can change the document template from advanced settings as shown below
  8. To add site columns to this content type, go to Site SettingsWeb Designer Galleries > Site content types > Click on newly created a content type (Cash Deposit)
  9. Click on Add from existing site columns
  10. Add the site columns to this content type. Here is an important point need to be noted. Add all the required site columns for this content type. In the below screenshot I have added only 3 but you can add as many as you want to make it different from other content types.
  11. Similarly, add another content type and name it Cash Withdrawal with some different site columns.
  12. Now both the content types are ready for use. Let’s add these content types to a Library named BankingSystem
  13. Go to Library Settings > Advanced settings > make sure the Allow management of content type is selected as shown below:
  14. Click on Add from existing site content types

  15. Add both the custom content types as shown below
  16. You can see both these content types are available under the New Document option

I hope you liked reading this article on SharePoint Content Types. If you have any questions feel free to as in the comment section below.

SharePoint Site Columns – Best Explained

Hello friends, in my 3 years of journey with SharePoint, I have never used SharePoint site columns. SharePoint provides the lightning fast way for creating list columns, which makes us lazy to learn about site columns. In this article, I will try to explain about SharePoint site columns in details. This applies to all versions of SharePoint like SharePoint 2010, 2013 and SharePoint Online (Office 365).

It takes a few seconds to create list columns
It takes a few seconds to create list columns

SharePoint Site Columns

According to Microsoft, “A site column is a reusable column definition, or template, that you can assign to multiple lists across multiple SharePoint sites. Site columns are useful if your organization wants to establish some consistent settings across lists and libraries.”

Why should we use SharePoint Site Columns?

Scenario:

Assume that your organization has a SharePoint portal which has 20 different lists. Each list contains a choice column named a country with 3 options as India, America, and England. later point of time, if you want to add one more country as China in the option for all the lists, what will you do? The only way available for you is to add that new option in each list manually from list settings.

In such scenarios, Site columns play an important role. Site columns allow you to share the changes/settings across multiple lists so that you don’t have to configure the settings each time. Site columns provide one more advantage to you, whenever you make any changes in site columns, it provides an option whether to apply the new changes to all the lists (which are using that particular site column) or not.

When you update the site column, it will ask whether to apply the changes on all lists which are using the particular site column
When you update the site column, it will ask whether to apply the changes on all lists which are using the particular site column.

How to Create a Site Column in SharePoint?

Before creating a Site Column you should make note of below important points

  1. It’s a best practice to create a Site Column under the root site (top site) so that it can be used under all subsites as well. This is again based on the requirements of the organization because users don’t want to have too many site columns under the root sites, which are not useful.
  2. If you create a Site Column in a subsite, you cant use that site column in your root site.
  3. When you update the site column, it’s your wish whether to apply the updates on existing lists or not (this point is already explained above).
  4. If you delete the site column, it won’t be deleted automatically from all the lists. You have to delete the site columns specifically from all the lists.

let’s see how to create a SharePoint site column:

  1. Go to Site Settings
  2. Click on Site columns under Web Designer Galleries
  3. Click on Create

  4. In the Name and Type section, type the name that you want in the Column name box. In this case we are creating a site column named Country.
  5. Choose the appropriate the column type like Singe line of text, Lookup, etc. In this case, Choice (India, America, and England)
  6. In the Group section, add this new Site column under existing groups or create a new one. Categorizing columns into groups will make it easier for users to find them in the future. In this case, we are adding this site column to a group named Custom Columns.
  7. Click on OK.

This way we are ready with the new site column, which can be used in all lists under the specified sites or subsites.

How to add site columns to existing SharePoint List or Library

Let’s add the newly created site column to the existing list. We have a list named EmployeeDetails where we are going to add a Site Column named Country which was added in Custom Columns group.

  1. Go to list settings
  2. Click on add from existing site columns

  3. Choose group so that it will be easy to find the custom site column. Then choose the site column name and click on Add
  4. Click on OK and we are ready to use this site column in our list.

How to update/delete site columns in SharePoint?

  1. Go to Site Settings
  2. Click on Site columns under Web Designer Galleries
  3. Click on Site Column name
  4. Update the site column and click OK or if you want to delete the column, click on Delete button.

I hope you liked this article. If you have any queries, please use below comments section for the same. Please like our facebook page and subscribe to our newsletter for future updates. Have a nice day! ta da…

CRUD Operations using REST API in SharePoint Online/2013/2010

  1. Hello folks, in this tutorial we are going to perform CRUD (Create, Read, Update and Delete) operations using REST API in SharePoint.

Learn how to perform CRUD (Create, Read, Update and Delete) operations using REST API in SharePoint List. You can use it for SharePoint Online, 2010, 2013 and 2016.
.

Create SharePoint list Item using REST API Read SharePoint list Item using REST API Update SharePoint list Item using REST API Delete SharePoint list Item using REST API

Setup required

We are using a SharePoint custom list named “EmployeeDetails” with below columns:

Column Name Type
EmloyeeName (internal name is Title) Single line of text
Address Multiple lines of text
Country Choice (India, US, UK)
Age Number
Salary Currency
DateOfBirth Date and Time
IsEmployeeMarried Checkbox
ManagerName Person or group
ProfileUrl Hyperlink

Download: You can download the template of this SharePoint list here.

Create Item:

//Create a SharePoint List Item using REST Api

function createItem() {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmployeeDetails')/Items",
        type: 'POST',
        headers: {
            "Accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "POST"
        },
        data: JSON.stringify({
            __metadata: {
                type: "SP.Data.EmployeeDetailsListItem"
            },
            Title: "Mayuresh Dinkar Joshi",
            Address: "ABC Center, Near Sdftji Dfrtg 123123 Test",
            Country: 'India',
            Age: 25,
            Salary: 1000,
            DateOfBirth: "1993-09-21T07:00:00Z",
            IsEmployeeMarried: true,
            ManagerNameId: 16, //internalName is 'ManagerName' but we have to use 'ManagerNameId' to pass id of a person
            ProfileUrl: {
                __metadata: {
                    "type": "SP.FieldUrlValue"
                },
                Url: "http://test.com",
                Description: "Url Description"
            },
        }),
        success: function(data) {
            alert('Item created successfully!');
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });
}

Read Item:

//Read a SharePoint List Item using REST Api

function readItem() {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmployeeDetails')/Items(1)",
        type: 'GET',
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            console.log(data.d);
            alert(" First name: " + data.d.Title +
                "\n Address: " + data.d.Address +
                "\n Country: " + data.d.Country +
                "\n Age: " + data.d.Age +
                "\n Salary: " + data.d.Salary +
                "\n DateOfBirth: " + data.d.DateOfBirth +
                "\n IsEmployeeMarried: " + data.d.IsEmployeeMarried +
                "\n ManagerName: " + data.d.ManagerNameId +
                "\n ProfileUrl: " + data.d.ProfileUrl.Url);
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });
}

Update Item

//Update a SharePoint List Item using REST Api

function updateItem() {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmployeeDetails')/Items(1)",
        type: "PATCH",
        headers: {
            "Accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*",
            "X-HTTP-Method": "MERGE"
        },
        data: JSON.stringify({
            __metadata: {
                type: "SP.Data.EmployeeDetailsListItem"
            },
            Title: "updated Mayuresh Dinkar Joshi",
            Address: "updated ABC Center, Near Sdftji Dfrtg 123123 Test",
            Country: 'US',
            Age: 26,
            Salary: 2000,
            DateOfBirth: "1993-09-22T07:00:00Z",
            IsEmployeeMarried: false,
            ManagerNameId: 16, //internalName is 'ManagerName' but we have to use 'ManagerNameId' to pass id of a person
            ProfileUrl: {
                __metadata: {
                    "type": "SP.FieldUrlValue"
                },
                Url: "http://test1.com",
                Description: "updated Url Description"
            },
        }),
        success: function(data) {
            alert('Item updated successfully!');
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    })
}

Delete Item

//Delete a SharePoint List Item using REST Api

function deleteItem() {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmployeeDetails')/Items(1)",
        type: 'DELETE',
        headers: {
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*",
            "X-HTTP-Method": "DELETE"
        },
        success: function(data) {
            alert('Item deleted');
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    })
}

Convert SharePoint Date to Readable date format using jquery

Hi friends, today we are going to see how to convert SharePoint date into human readable date format using jquery.

When you use REST API or JSOM to retrieve the date field from SharePoint, you will get the output as /Date(1508371200000)/. But what if you need it in a readable format?

We can easily convert above date format into a human-readable format using below script. Here

var rawDate = "/Date(1508371200000)/"; 
var rawDate = parseInt(rawDate.substring(6, 19)); 
var d = new Date(rawDate); 
var result = d.format("dd MMM yyyy");

In the above code, the variable result will give you the output as 19 Oct 2017

Convert SharePoint date to Readable date
Convert SharePoint date to Readable date

Recommended articles:

  1. CRUD Operations using REST API in SharePoint
  2. SharePoint Interview Questions
  3. SharePoint Content Types – Best Explained
  4. How to Make Conditionally Mandatory Field in SharePoint 2013
  5. SharePoint Site Columns – Best Explained

I hope you liked this article. Please feel free to ask your queries in the comment section below. Like our facebook page, and subscribe to our newsletter for future updates. Have a nice day!

How to Display SharePoint List in jQuery Datatables

Hello friends, in this article we are going to retrieve data from SharePoint List using REST API and will display that data into jQuery Datatable. So let’s begin…

Show SharePoint List in Datatable format

Step 1:

We have a SharePoint list named EmployeeDetails as shown below with some dummy data. This list has 4 columns (Title, Name, Salary, Address).

EmployeeDetails List
EmployeeDetails List

Step 2 : Create a site page where we are going to show above data in datatable. For creating a page go to Site contents > Site pages > Click on new page icon. In this case I have created a page with name Employee Details.

Step 3 : Insert a Content Editor Webpart into a page.

Employee Details Page
Employee Details Page

Step 4 : Edit the Content Editor Webpart and paste the below code into it.

 

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../SiteAssets/EmployeeJqueryDatatable.js"></script>
<div id="DatatablePanel">
    <table style="width: 100%;">
        <tr>
            <td>
                <div id="DatatableGrid" style="width: 100%"></div>
            </td>
        </tr>
    </table>
</div>

download above html file here. (or you can use MediaFire link)

Step 5 : If you can observe the above code, we have referenced a .js file named EmployeeJqueryDatatable.js So we have to first create this js file and upload it into Site assets. Please copy the below code into this js file and named it as EmployeeJqueryDatatable.js

$(document).ready(function() {
    var RestUrl = "../_vti_bin/listdata.svc/EmployeeDetails";
    $.ajax({
        url: RestUrl,
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            if (data.d.results.length > 0) {
                //construct HTML Table from the JSON Data
                $('#DatatableGrid').append(GenerateTableFromJson(data.d.results));
                //Bind the HTML data with Jquery DataTable
                var oTable = $('#EmployeeTable').dataTable({
                    "iDisplayLength": 5,
                    "aLengthMenu": [
                        [5, 10, 30, 50],
                        [5, 10, 30, 50]
                    ],
                    "sPaginationType": "full_numbers"
                });
            } else {
                $('#DatatableGrid').append("<span>No Employee Details Found.</span>");
            }
        },
        error: function(data) {
            $('#DatatableGrid').append("<span>Error Retreiving Employee Details. Error : " + JSON.stringify(data) + "</span>");
        }
    });

    function GenerateTableFromJson(objArray) {
        var tableContent = '<table id="EmployeeTable" style="width:100%"><thead><tr><td>Title</td>' + '<td>Name</td>' + '<td>Salary</td>' + '<td>Address</td>' + '</tr></thead><tbody>';
        for (var i = 0; i < objArray.length; i++) {
            tableContent += '<tr>';
            tableContent += '<td>' + objArray[i].Title + '</td>';
            tableContent += '<td>' + objArray[i].Name + '</td>';
            tableContent += '<td>' + objArray[i].Salary + '</td>';
            tableContent += '<td>' + objArray[i].Address + '</td>';
            tableContent += '</tr>';
        }
        return tableContent;
    }
});

download above .js file here (for security reasons I have used .txt file here, so after downloading rename it to .js) or you can use MediaFire link to download the direct js file here

Step 6 : Once you upload the above js file into your site assets, go to our EmployeeDetails page that we ceated in step no. 2. Here we go!!! below is the output for our EmployeeDetails list

Video tutorial:

I have also created a step by step video tutorial for SharePoint Datatables. Please watch it for clear understanding:

https://www.youtube.com/watch?v=gXoeBrXSb3A

I would like to reply to your queries. Please let me know whether you liked this simple step by step article on SharePoint Datatable integration. I am waiting for your comments! Please like our facebook page and subscibe to our newsletter for future updates. Have a nice day!

Cascading drop-downs using Lookup fields in SharePoint using SPServices

Hi friends, in this tutorial we are going to implement cascading of lookup fields in SharePoint using SPServices:

Lets take a simple example of Country > State cascading.

We have one Country List in which we are storing our Country values in Title field.

Country List
Country List

We have another list named States, in which we are storing state values in Title field. This list also has a lookup field named Country in which we are storing corresponding countries from Country List.

States List
States List with Country as Lookup field

Now we have third list named Information in which there are two lookup fields: Country and State

Information List with Country and State as lookup fields
Information List with Country and State as lookup fields

Just add below script in Content editor webpart on NewItem and EditItem page.

<script src="//code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $().SPServices.SPCascadeDropdowns({
        relationshipList: "States",
        relationshipListParentColumn: "Country",
        relationshipListChildColumn: "Title",
        parentColumn: "Country",
        childColumn: "State",
        debug: true
    })
})
</script>

If you want three level of cascading like Country > State > City, you can modify the code as below:

<script src="//code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $().SPServices.SPCascadeDropdowns({
        relationshipList: "States",
        relationshipListParentColumn: "Country",
        relationshipListChildColumn: "Title",
        parentColumn: "Country",
        childColumn: "State",
        debug: true
    })
    $().SPServices.SPCascadeDropdowns({
        relationshipList: "City", // This will be a name of City List
        relationshipListParentColumn: "States", // This will be a name of State list
        relationshipListChildColumn: "Title",
        parentColumn: "State",
        childColumn: "City",
        debug: true
    })
})
</script>

Watch below YouTube video created by me, which will explain the process in details:

If you liked this article, please share your comments below. Let me know if you face any issues. Like our facebook page for future updates. Have a nice day!