Monday, 25 September 2017

Validate a URL field

This set of code will validate the multi line text field and checks whether the URL entered  is valid or not. If not valid, disable the "Submit" button.


$(document).ready(function () {

    validateURL();


});

// This method is used to validate the url. If url is not valid, disable the submit button.
function validateURL() {

    $("#txtURLField").change(function () {
        if (checkUrl($("#txtURLField").val())) {
            $("#btn-id-submit").prop('disabled', false);
        }
        else {
            $("#btn-id-submit").prop('disabled', 'disabled');
            alert("Please enter a valid URL");
        }
    });
}

// This method has the URL validation properties.
function checkUrl(url) {
    //regular expression for URL
    var pattern = /^(http|https)?:\/\/[a-zA-Z0-9-\.]+\.[a-z]{2,4}/;

    if (pattern.test(url) || (url == "")) {
        return true;
    } else {
        return false;
    }

}

------------------------------------------END------------------------------------------------

Get HTML dropdown field values from SharePoint choice list column.

// Call methods on page load
$(function () {

    var ddl1 = bindDropdownValues("ColumnName1", "#ColumnName1_Id");
    var ddl2 = bindDropdownValues("ColumnName2", "#ColumnName2_Id");
    var ddl3 = bindDropdownValues("ColumnName3", "#ColumnName3_Id");

});

// This will make a rest call and on success of that, it will bind the list choice fields values to form dropdown controls.
function bindDropdownValues(columnName, ControlID) {
    var dfd = new $.Deferred();
    getChoiceValues("" + columnName + "").done(function (platformValues) {

        $.each(platformValues.d.results[0].Choices.results, function (key, values) {

            $("" + ControlID + "").append($("<option class='ddlValues'></option>").text(values));
        });
        dfd.resolve();
    });
    return dfd.promise();
}

// This is the rest call to get the list choice field data.
function getChoiceValues(columnName) {
    return $.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('LIST NAME HERE')/fields?$filter=EntityPropertyName eq '" + columnName + "'",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
    });

}


--------------------------------------------END----------------------------------------------

SharePoint custom People Picker

Add the following references to HTML:

<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>

<script type="text/javascript" src="/_layouts/15/autofill.js"></script>

HTML Content:

<label for="AssignedTo">Assigned To</label>
<div id="AssignedTo"></div>
<label for="CopyTo">Copy To</label>

<div id="CopyTo"></div>


JavaScript Content:


// Call methods on page load
$(function () {

    SP.SOD.registerSod('sp.js', '/_layouts/sp.js');

    // Call this method to initialize the people picker
    initializePeoplePicker("AssignedTo"); // People Picker 1
    initializePeoplePicker("CopyTo");   // People Picker 2


    // Call this method in edit form. This method will get the data from the list using the // item id and bind the names in page load.
    var pickerVal = BindUsersFromList();
});



// This method will take the div ID as parameter and converts that to a people picker.
// peoplePickerElementId: Div ID
function initializePeoplePicker(peoplePickerElementId) {

    // Create a schema to store picker properties, and set the properties.
    var schema = {};
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    // "AllowMultipleValues" property will allow multiple entries. Make it false to restrict //this people picker to accept only one  user.
    schema['AllowMultipleValues'] = true;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = 'auto';

    // 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);

}


Note:
The above JS code will convert the HTML div into a people picker.
Now the below JS code will get the data from the SharePoint list using item ID and bind the values to people picker.



// This method will bind the users to people picker field in edit form.
function BindUsersFromList() {

    var dfd = new $.Deferred();
    var divPeopleSIT = SPClientPeoplePicker.SPClientPeoplePickerDict["AssignedTo_TopSpan"];
    var divPeopleAMM = SPClientPeoplePicker.SPClientPeoplePickerDict["CopyTo_TopSpan"];

    SP.SOD.executeFunc('sp.js', null, function () {
        JSRequest.EnsureSetup();
        var itemID = JSRequest.QueryString["ItemID"];
        if (window.location.href.indexOf('ItemID=') > -1) {
            var call = getEditformDataFromList(itemID);

            $.when(call).then(function (data) {
                if (data.d.AssignedToId != null) {
                    for (var i = 0; i < data.d.AssignedToId.results.length; i++) {
                        divPeopleTSDM.AddUnresolvedUser({ 'Key': GetUserLoginName(data.d.AssignedToId.results[i]) }, true);
                    }
                }
                if (data.d.CopyToId != null) {
                    for (var i = 0; i < data.d.CopyToId.results.length; i++) {
                        divPeopleSIT.AddUnresolvedUser({ 'Key': GetUserLoginName(data.d.CopyToId.results[i]) }, true);
                    }
                }
            });
            dfd.resolve();
        }
    });
    return dfd.promise();
}

// This rest call will take the item ID as input and give that Item data in return.
// itemID: List Item ID
function getEditformDataFromList(itemID) {

    return $.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('LIST NAME HERE')/items(" + itemID + ")",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
    });
}

// This will take the People picker Id and return the entered user's Login Name
function GetUserLoginName(pickerID) {
    var userName;
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/GetUserById(" + pickerID + ")",
        type: "GET",
        async: false,
        headers: {
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-type": "application/json;odata=verbose",
            "accept": "application/json;odata=verbose"
        },
        success: function (userData) {
            userName = userData.d.LoginName;
        }
    });
    return userName;

}


Now, get the number of users entered in the people picker field.


var getUsersData = getUserIdsFromPicker(valObj.Id);
var length = getUsersData.length;

// Get the user ids of the persons entered in the people picker
// divID: ID of the div/PeoplePicker
function getUserIdsFromPicker(divID) {
    var pickerDiv = "#" + divID + "";
    noOfUser = $(pickerDiv + "_TopSpan_ResolvedList").children().length;
    userIds = new Array(noOfUser);
    $(pickerDiv + "_TopSpan_ResolvedList").children().each(function (index, value) {
        $.when(GetUserId($(this).attr("sid"))).then(function (data) {
            userIds[index] = data.d.Id;
        });
    });
    return userIds;
}

// This will return a object which will have the user Ids of the person.
// userName: SID of the user
function GetUserId(userName) {
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    return $.ajax({
        url: siteUrl + "/_api/web/siteusers(@v)?@v='" +
            encodeURIComponent(userName) + "'",
        method: "GET",
        async: false,
        headers: { "Accept": "application/json; odata=verbose" },
    });

}


------------------------------------------------------------------END--------------------------------------------------------------



Thursday, 12 January 2017

How to create Collapse and Expand section in InfoPath



  • Create an InfoPath form as shown below.
  • Add a section to this form.

  • Add two buttons ( Expand & Collapse symbols). 

  • Now create a column ( Flag) of Boolean type. It will have value 0 or 1. Set default value as "1".
  • Write the rules on two buttons ( Expand & Collapse) for setting the values of flag column. On "Expand(+)", set value to 1 and on "collapse(-)", set value to 0.

  • And also write rule for display either one at a time. Means if one is button displaying another should be hidden.

  • On "Expand(+)", set flag to 1 and on "collapse(-)", set flag to 0.

  • Finally for the section to collapse or expand, write an action on the section. If Flag = 0, hide the section.



Wednesday, 11 January 2017

Authentication in SharePoint


There are 2 types of authentication  in SharePoint.

     1. User Authentication
     2. App Authentication

Click here to get the high level understanding on authentication & authorization.

User Authentication can be done in 3 ways.

  •  Windows Based Authentication 
  •   Form Based Authentication
  •   Token Based Authentication.
Click here to get details on user authentication. 

App Authentication can be done using OAuth.

Details on OAuth.

 Click here to get basics of OAuth  - 1

Click here to get basics of OAuth  - 2

Click here to get basics of OAuth  - 3






Wednesday, 4 January 2017

How to redirect to home page after submitting/closing InfoPath form:

     
  Ø     Go to the list and click on add new item.
  Ø    After the form appears, copy the URL.

Example:
http://ABCD1234:1234/sites/MY_SITE/Lists/MY_LIST/Item/newifs.aspx?List=5c408_TEST237464fa%2D4571%2D8ccb%2D782f9DHFD779D&Source=http_TEST%3A%2F%2FABCD1234:1234%3A2407%2Fsites%MY_SITE%2FLists%2FMY_LIST%2FAllItems%2Easpx&RootFolder=& Web=1c43f31645642%2_TESTD1004%2D671c7%2D96c0%2D5c62515af56785

http:// SERVER NAME /sites/ SITE NAME /Lists/LIST NAME /Item/newifs.aspx?List=LIST ID &Source=WRITE THE URL WHERE YOU WANT TO REDIRECT AFTER SUBMIT/CLOSE &RootFolder=&Web=WEB ID

  Ø  Suppose you have a button or anchor tag in home page as mentioned below, on click of which it is opening the InfoPath form.

Example:
<button type="button" onclick="location.href = #" class="btn_class" style="padding: 19px 75px; border: medium none currentcolor; text-align: center; color: white; font-size: 17px; text-decoration: none; margin-top: -8px; margin-left: 310px; display: inline-block; cursor: pointer; background-color: #002966;"> Click Me !!! </button>
Or
<a href=" # ">Click me</a>

  Ø    Go to edit page and Open the button content by clicking on “Edit Source”.
  Ø    In the above two examples replace the “#” with the URL mentioned above.
  Ø    Save the page.
  Ø    Note: Careful while coping the new form url. Only edit that portion of the url where it mentioned “WRITE THE URL WHERE YOU WANT TO REDIRECT AFTER SUBMIT/CLOSE.” It is not required to change the other portions. Means only source link (Source=) needs to be changed.




Tuesday, 20 December 2016

Process for creating a SharePoint Master Page from a HTML page.


1. Create your HTML master page on local with proper styles. 
   Check if this HTML page works on all browsers. Especially on IE and Chrome. For Office 365 sites also check for Mozila.
   
2. Go to Site Action --> Site Settings --> Web Designer Galleries --> Master pages and page layouts. 

3. Create a folder for your master page and upload all your master page files. 

4. While uploading the html page select the "HTML master page" from the drop down. And for other files select "Custom".

5. After successfully uploaded all the files. Go to Site Action --> Design Manager --> Edit Master Page

6. Find your master page folder here which you have created in "Master pages and page layouts".

7. Open the folder and select the HTML page and on the top click "Convert an HTML file to a SharePoint master page".

8. It will open a wizard, there again go inside your folder, select HTML file, click insert. 

9. After insert you must see the conversion successful message status for that respective HTML page. If you are getting conversion error, don't try to publish as major version. 
   Correct the HTML file, upload again. Only publish when you get conversion successful message. 

10. Now your master page is created. But it is not yet listed in the master page list(Site Action --> Site Settings --> Look and Feel --> Master Page). 

11. To make it listed on the master page list, right click on master page and select "Publish as major version".

12. Now your master page is listed. To change the master page, go to Site Action --> Site Settings --> Look and Feel --> Master Page and select your master page from the dropdown.