We have a requirement to filter Look-up drop-down values based on the current logged in user.

Incident List:

Title Single Line of Text
Description Multiple Lines of Text
Site Lookup to “Sites” list (single select)

By default, “Site” lookup field will display all items from “sites” list. But, in our case drop-down should show only sites assigned to current user.

“Sites” List:

SiteName UserName
Site A User1
Site B User2; User3
Site C User3

Leveraged SP services and implemented client side code to achieve this functionality.

In this case, user2 will only see “Site B”.


<script type="text/javascript" src="/Style Library/Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="/Style Library/Scripts/jquery.SPServices-0.6.2.min.js"></script>

<script language="javascript" type="text/javascript">

/* Get Field by Title */

function getField(fieldType,fieldTitle) {
      var docTags = document.getElementsByTagName(fieldType);
      for (var i=0; i < docTags.length; i++) {
          if (docTags[i].title == fieldTitle) {
              return docTags[i];
          }
      }
      return false;
}

function updateValues(newSites) {
	lookupFieldText = getField('input','Site');
	lookupFieldId = document.getElementById(lookupFieldText.optHid);
	lookupFieldText.choices = newSites;
}

$(document).ready(function() {

/* Get Current username */

var userName = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });

/* Get Sites assigned to current user */
var query = "<Query><Where><contains><FieldRef Name='UserName' /><Value Type='User'>" +
			userName + "</Value></contains></Where></Query>";

$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Sites",
    CAMLQuery: query,
    CAMLQueryOptions: "<QueryOptions><ViewAttributes Scope='RecursiveAll' IncludeRootFolder='True' /></QueryOptions>",
    CAMLViewFields: "<ViewFields><FieldRef Name='SiteName' /></ViewFields>",
    completefunc: function (xData, Status) {
      var newSites = "(None)|0|";
      $(xData.responseXML).find("[nodeName='z:row']").each(function() {
      	var IDLookup = $(this).attr("ows_SiteName").split(";#").shift();
		var TitleLookup = $(this).attr("ows_SiteName").split(";#").pop();
		if( TitleLookup != '' )
		{
			var newValue = TitleLookup + "|" + IDLookup + "|";
			if( newSites.indexOf(newValue) == -1 )
			{
				newSites = newSites + newValue;
        	}
        }
      });
      newSites = newSites.substring(0, newSites.length-1);
      updateValues(newSites);
    }
  });
});

</script>
Advertisements