Monday, August 14, 2017

SharePoint Online: Set the default value for a Lookup (SPFieldLookupMulti) column

The following code will set the value for a Lookup field in SharePoint, where the highlighted fields are what you'd need to update.

           // define the items to add to the results (i.e already selected) this the visual part only  
           var $resultOptions = "<option title='Veeva Vault' value='3'>Veeva Vault</option>";  
           // this is the list of initial items (matching the ones above) that are used when the item is saved.  '|t' is the divider
           var $resultSpOptions = "3|Veeva Vault";  
            
           // remove the option selected on the left side.  NOTE: These are in alphabetical order and thus this ID will probably differ from the select ID (and is 0 based)
           $("[id$='_SelectCandidate'] option:eq(2)").remove(); 

           // append the new options to our results (this updates the display only of the second list box)  
      $("[id$='_SelectResult']").append($resultOptions); 
            // append the new options to our hidden field (this sets the values into the list item when saving)  
      $("[id$='MultiLookup']").val($resultSpOptions);   

You can get the values by using the developer tools (e.g. pressing F12 in Chrome) and inspecting the picker element:



you'll see:


where targeting 3 would result in the code above.

Shout out to this blog post which helped, just needed some minor tweaks to work in SharePoint Online.

Wednesday, August 9, 2017

Setting the default value for a Rich Text Field in SharePoint Online

To set the default value of a Multiple Lines of Text aka Rich Text Field aka SPFieldNote you can use the following JavaScript:

<script type="text/javascript">
$(document).ready(function () {

var defaultText = "Your html here";

                $('nobr:contains("[Your Field Title]")').closest('tr').find('div.ms-rtestate-write').html(defaultText);

});
</script>

Monday, August 7, 2017

Show the List Title in form views (NewForm.aspx, EditForm.aspx, DispForm.aspx)

Whenever the ribbon is being shown the title of the list will not be displayed:


So the user might not have any context to where they are.  So to add the Title of the list, use the following css into the PlaceHolderPageTitleInTitleArea content placeholder for NewForm.aspx, EditForm.aspx and DispForm.aspx pages in SharePoint Designer:

<style> 
    #s4-titlerow { 
display: block !important; 
    } 
</style> 

into:



And then you'll have a title in your form:






Get a user from a Person field and check if they are in a SharePoint group

If you have a Person field (people picker) in your SharePoint form, and need to get that value, check if they're in a group, and take an action based on that, you can use the following:

<script type="text/javascript">

function IsCurrentUserMemberOfGroup(groupName, pickerTitle, OnComplete) {

// get people picker
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[$('[title="' + pickerTitle + '"]')[0].id];

// get the user dictionary
    var users = peoplePicker.GetAllUserInfo();
   
    // get the user name
   var currentUserAccountName = users[0]['Key'];
       
      // get current context and web
      var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();
                
        // get the user object
        var user = currentWeb.ensureUser(currentUserAccountName);
         
        // execute call to get user id
        currentContext.load(user);
    currentContext.executeQueryAsync(
        Function.createDelegate(null, OnUserSuccess), 
        Function.createDelegate(null, OnUserFailure)
   );

var groupUsers;

// Once we have the user, check if they're in the group
function OnUserSuccess(sender, args) {

// get all groups
var allGroups = currentWeb.get_siteGroups();
       currentContext.load(allGroups);

// get the group we're looking for
       var group = allGroups.getByName(groupName);
       currentContext.load(group);

// get the users of the group
       groupUsers = group.get_users();
       currentContext.load(groupUsers);

       currentContext.executeQueryAsync(OnGroupSuccess,OnGroupFailure);
}

// loop through all users in the group and look for our user
        function OnGroupSuccess(sender, args) {
            var userInGroup = false;
            var groupUserEnumerator = groupUsers.getEnumerator();
            while (groupUserEnumerator.moveNext()) {
                var groupUser = groupUserEnumerator.get_current();
                if (groupUser.get_id() == user.get_id()) {
                    userInGroup = true;
                    break;
                }
            }  
            OnComplete(userInGroup);
        }
        
        function OnUserFailure(sender, args) {
OnComplete(false);
}


        function OnGroupFailure(sender, args) {
            OnComplete(false);
        }    
}

function IsCurrentUserHasContribPerms() 
{
  IsCurrentUserMemberOfGroup("Leadership Team", "Nominee", function (isCurrentUserInGroup) {
    if(isCurrentUserInGroup)
    {
        alert('Leadership Team Members are not eligible to be nominated');
        $("input[value$='Save']").attr('disabled', true);
        $("span[id='Person']").css('color','red').css('font-weight','bold');
    }
    else {
    $("input[value$='Save']").attr('disabled', false); 
    $("span[id='Person']").css('color','black').css('font-weight','normal');
    }
  });
}


function SetOnChangeEvent() 
{
$('input[title="Nominee"]').blur(function(){
IsCurrentUserHasContribPerms();
});
}

$(document).ready(function(){ 

ExecuteOrDelayUntilScriptLoaded(SetOnChangeEvent, 'SP.js');

});
</script>