In my recent blog entry I’ve illustrated how to change the out-of –the-box display order of the enterprise custom fields in the “Details” web part on the Project Details page of Project Server. In this post I go one step further and show, how to display / hide the fields based on conditions. As in the previous case, I use jQuery in this case either to achieve the goal.
For the sake of example, let’s assume you have a few custom fields (in this case “Field1” and “Field2”) that should be displayed only for the members of a special SharePoint group called “Admins”.
The script we need in this case is displayed in the code snippet below:
- var adminGroup = "Admins";
- function isCurrentUserMemberOfGroup(groupName, OnComplete) {
- var clientContext = new SP.ClientContext.get_current();
- var currentUser = clientContext.get_web().get_currentUser();
- var userGroups = currentUser.get_groups();
- clientContext.load(userGroups);
- clientContext.executeQueryAsync(OnSuccess, OnFailure);
- function OnSuccess(sender, args) {
- var isMember = false;
- var groupsEnumerator = userGroups.getEnumerator();
- while (groupsEnumerator.moveNext()) {
- var group = groupsEnumerator.get_current();
- if (group.get_title() == groupName) {
- isMember = true;
- break;
- }
- }
- OnComplete(isMember);
- }
- function OnFailure(sender, args) {
- OnComplete(false);
- }
- }
- $(document).ready(startScript);
- function setFieldVisibility(fields, visible) {
- // hide status / twitter related fields
- $(".ms-accentText").each(function (index) {
- if ($.inArray($(this).text(), fields) != -1) {
- $(this).closest('tr').toggle(visible);
- }
- });
- }
- function startScript() {
- var fieldsToHide = ["Field1", "Field2"];
- // hide the fields at page startup
- setFieldVisibility(fieldsToHide, false);
- isCurrentUserMemberOfGroup(adminGroup, function (isCurrentUserInGroup) {
- console.log("Current user is member of group '" + adminGroup + "': " + isCurrentUserInGroup);
- setFieldVisibility(fieldsToHide, isCurrentUserInGroup);
- });
- }
We use the setFieldVisibility function to hide / display the fields. On the page load we hide the fields in the first step. To verify if the current user belongs to the group and to perform a custom action after the check I use the isCurrentUserMemberOfGroup function borrowed from Stack Overflow. Finally, we set the visibility of the field in the callback function based on the group membership of the current user.
Assuming this script is saved in the file DisplayFieldsForGroup.js in the Site Assets library of the PWA site, and the jquery-1.9.1.min.js can be found in that library as well, you can add a Script Editor web part to the Project Details page, and include these two lines in the web part to inject the functionality into the page:
/PWA/SiteAssets/jquery-1.9.1.min.js
/PWA/SiteAssets/emDisplayFieldsForGroup/em.js
