Sanjaya on SharePoint/Microsoft technologies

a blog on technologies like .net, MOSS 2007, wss 3.0 etc

  • Flickr Photos

Posts Tagged ‘Filter items in a lookup field’

Filtered lookup field in sharepoint list

Posted by sNjY on February 21, 2008

Recently, I had a requirement where i wanted to filter my lookup field items in a sharepoint list based on some conditions. I found this article, which talks about the same.

http://blog.u2u.info/DottextWeb/patrick/articles/466.aspx

Good article, but for some reason i was not getting the id field for my combo.

Then i figured out the following way of doing the same. its all with the beauty of xml and java script.

It has worked for me, so here it goes, may be this helps for some of us.

1. First create an aspx page with your logic, validations to fetch the items you want to set to the lookup field. Copy the page to 12\TEMPLATE\LAYOUTS to make it an application page. The code should be something like this, where you fetch your values, prepare an xml data and write it to the HTTPResponse.

protected void Page_Load(object sender, EventArgs e){SPWeb web = SPControl.GetContextWeb(this.Context); this.Response.ClearHeaders();this.Response.ClearContent();

this.Response.Cache.SetCacheability(HttpCacheability.NoCache);this.Response.AddHeader(“Content-type”, “text/xml”);

string cmdPattern = @”<Command><Value><![CDATA[{0}]]></Value><Text><![CDATA[{1}]]></Text>

</Command>”;this.Response.Write(@”<?xml version=””1.0″” encoding=””UTF-8″” ?>”);

this.Response.Write(“<Commands>”);//SPView myProjects = web.Lists[“e-PSFs”].Views[“Newly Approved ePSFS”];

SPListItemCollection items = web.Lists[“e-PSFs”].Items; foreach (SPListItem item in items){//Filter the values based on your conditions and write it to the reponse one by one

if ( Convert.ToString(item[“Status”])==“Approved”){this.Response.Write(string.Format(cmdPattern, Convert.ToString(item[“ID”]), Convert.ToString(item[“Title”])));}}

this.Response.Write(“</Commands>”);this.Response.End();web.Dispose();}

At this point, we have our aspx page ready to fetch our items and write it to the HTTPReponse.

2. Add the following javascript section to your page like newform.aspx, editform.aspx etc

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

_spBodyOnLoadFunctionNames.push(“FillLookupFieldItems”);
}
function FillLookupFieldItems()
{
 var ePSFCombo=getTagFromIdentifierAndTitle(‘select’,’Lookup’,’ePSF’);
 if(ePSFCombo==null)
 {
  ePSFCombo=getTagFromIdentifierAndTitle(‘input’,”,’ePSF’);
 }
 
  var request;
  var url = window.location.toString().substring(0,window.location.toString().indexOf(window.location.pathname)) +
      “/_layouts/ISSA/NewlyApprovedePSFs.aspx”; //NewlyApprovedePSFs.aspx is the aspx page we create in step 1.
   if ( window.XMLHttpRequest )
   {
      request = new XMLHttpRequest();
      request.open(“GET”, url, false);
      req.send(null);
   }
   else if ( window.ActiveXObject )
   {
      request = new ActiveXObject(“Microsoft.XMLHTTP”);
      if ( request )
      {
         request.open(“GET”, url, false);
         request.send();
      }
   }
  
   if ( request )
   {  
  
      var commands = request.responseXML.getElementsByTagName(“Command”);
      // for each command found in the returned XML, extract the Text,
      // and value of the item
      ePSFCombo.options.length=0;
   var none=document.createElement(“OPTION”);
   ePSFCombo.options.add(none);
    none.innerText = ‘(None)’;
   none.value = 0;
  
      for ( var i = 0; i < commands.length; i++ )
      {
         var value = commands[i].getElementsByTagName(
            “Value”)[0].firstChild.nodeValue;
         var text = commands[i].getElementsByTagName(
            “Text”)[0].firstChild.nodeValue;
    
   var opt = document.createElement(“OPTION”);
   ePSFCombo.options.add(opt);
   opt.innerText = text;
   opt.value = value;
   
      }
          setSelectedOption(ePSFCombo,0);
         
   }

}

function setSelectedOption(select, value) {
  var opts = select.options;

  var l = opts.length;

  if (select == null) return;

  for (var i=0; i < l; i++) {

    if (opts[i].value == value) {

      select.selectedIndex = i;

      return true;

    }

  }

  return false;

}

function getTagFromIdentifierAndTitle(tagName, identifier, title) {

  var len = identifier.length;

  var tags = document.getElementsByTagName(tagName);

  for (var i=0; i < tags.length; i++) {

    var tempString = tags[i].id;

    if (tags[i].title == title && (identifier == “” || tempString.indexOf(identifier) == tempString.length – len)) {

      return tags[i];

    }

  }

  return null;

}

</script>

You are ready to go.

Please share if you have some other way of doing this.

Posted in Technology | Tagged: , , , , , | 15 Comments »