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--------------------------------------------------------------