Wednesday, September 11, 2013

SharePoint: Disable certain columns on New and Edit forms for few users

Recently, we had a requirement where in certain status fields for some lists are enabled for only few users when users create new items or edit existing columns.
Here is what we did to achieve this.
On both new and edit forms for the list, add a "Script Editor" web part. This web part allows us to write some jscript or jQuery as part of the page. Idea is to use SharePoint Client Object Model to access fields based on the current user. If the user is within the group specified we do not do anything otherwise disable the 'Status' field on the forms.
Here is the code to put inside "Script" tag.
SP.SOD.executeOrDelayUntilScriptLoaded(retrieveAllUsersInGroup, "SP.js");
function retrieveAllUsersInGroup() {
    var siteUrl = 'Replace site url here';
    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(replace group id as integer);
    this.collUser = oGroup.get_users();
    currentUser = clientContext.get_web().get_currentUser();
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
function onQuerySucceeded() {
    var userEnumerator = collUser.getEnumerator();
    var found = false;
    while (userEnumerator.moveNext()) {
        var oUser = userEnumerator.get_current();
        if (currentUser.get_title() == oUser.get_title())
            found = true;
    if (!found)
    {   $("select[title='Status']").attr("readonly","true").css('background-color','lightgray');
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());}

NOTE: Make sure to replace site url and group id in the above code. And the field disabled is 'Status' dropdown.

No comments:

Post a Comment