Advertisement

  • How to: Programmatically Create a New FilteredLookup Field

    A popular question on the FilteredLookup field is how to programmatically create one.

    I've put together the code snippet below to demonstrate one of the ways to go about creating the field from code:

      private static void AddFilteredLookupByXml() {
        try {
          // set target site as appropriate
          using (SPSite site = new SPSite("http://localhost/")) {
            // set target web as appropriate
            using (SPWeb web = site.RootWeb) {
              // the source list, i.e. where data will be retrieved from
              SPList sList = web.GetList("/Lists/Tasks");
              // the target list, i.e. the list that will contain the lookup field
              SPList tList = web.GetList("/Lists/FilteredItems");
     
              // the query to use to filter retrieved data
              string q = "<Where><Eq><FieldRef Name="Status" /><Value " +
                "Type="Text">In Progress</Value></Eq></Where></Query>";
     
              // the CAML xml fragment for the new FilteredLookup field
              string xml = string.Format("<Field ID=\"{0}\" " +
                  "StaticName=\"{1}\" Name=\"{1}\" " +
                  "Type=\"FilteredLookup\" DisplayName=\"My FilteredLookup Tasks\" Required=\"FALSE\" " +
                  "WebId=\"{2}\" List=\"{3}\" ShowField=\"{4}\"/>",
                // the ID (GUID) of the new FilteredLookup field
                  "{b28aa3a5-c186-49e1-b0f6-e9a949ffffff}",
                // the Name and StaticName of the new FilteredLookup field
                  "MyFilteredLookup_Task",
                sList.ParentWeb.ID, // GUID of the source web
                sList.ID, // GUID of the source list
                sList.Fields.GetFieldByInternalName("Title").Id // GUID of the source column
              );
     
              string fn = tList.Fields.AddFieldAsXml(xml); // add new FilteredLookup field as xml
              tList.Update(); // update target list
     
              FilteredLookupField f = ((FilteredLookupField)tList.Fields.GetFieldByInternalName(fn));
              // Don't set both query filter and view filter. ONLY set one or the other
              f.QueryFilterAsString = q; // set query filter
              //f.ListViewFilter = "";
              f.AllowMultipleValues = false; // set allow multiple values
              // set whether query is recursive. This ONLY applies to query filter
              f.IsFilterRecursive = true;
              f.Update(true); // finally update the new FilteredLookup field
            }
          }
        }
        catch (Exception e) {
          e.Source = "AddFilteredLookupByXml";
          throw e;
        }
      }


    The SharePoint FilteredLookup and its source codes are available for download on the codeplex website.

7 comments:

  1. Anonymous says:

    Hi Raphael thanks a lot for your tips. One question for you: if I want to set props:
    ListViewFilter (string) and LookupField (string)
    This string are simple string or must be in xml mode (like the query in you example?).
    Best regards
    MaxAmbrogi.com

  1. Raphael Iloh says:

    Max,
    The ListViewFilter property refers to the ID of the list view.
    E.g.
    f.ListViewFilter = sList.Views[enter name of view here].ID;

    For the LookupField, that's exactly the same as the ShowField contained in the CAML fragment. However, you may change the value programmatically by setting its new value to the Id of the appropriate source column.

    E.g.
    f.LookupField = sList.Fields.GetFieldByInternalName(enter name of column here).Id;

    And don't forget to update the field after such changes.

    HTH

  1. Anonymous says:

    Thanks a lot, I was struggled with this 1 day, finally I found your solution here. thank you very much.

  1. Sruli Ganor says:

    I used your code to set AllowMultiplevalues for a FilteredLookup and it worked.
    Thanks.

    I wonder why calling field.SetCustomProperty("SupportsMultipleValues", "True") did npt work.

    TIA
    Sruli

  1. Jonathan Galdames says:

    Hi Raphael, thanks for this tip.

    I don't know what happen with my code. I have implemented your solution and I am trying create a new FilteredLookpField by code with this tip, but I have this exception:

    Unable to cast object of type 'Bronyx.SharePoint.FieldControls.FilteredLookupField' to type 'Bronyx.SharePoint.FieldControls.FilteredLookupField'

    This exception happen in :

    FilteredLookupField f = ((FilteredLookupField)tList.Fields.GetFieldByInternalName(fn));

    Regards.

    PS: The FilteredLookupField found if I change the value of IDs properties (web, list, listview) from other siteCollection?

    And sorry for my english :)

  1. Jonathan Galdames says:

    Hi,

    I've solved my problem posted above.
    I was using source class instead of compiled class reference.

    Thanks.

  1. Jonathan Galdames says:

    Hi, again :)

    Well, only if anybody have a doubt.

    When you use

    list.AddFielsdAsXml(xml);

    You don't need assign manualy the ID of Field, like in the example above.

    Best regards.