Friday 14 September 2012

Event receiver rewire lookup

In my previous three posts, we demonstrated how to:

  • Create site columns
  • Create lookup fields
  • Create content types
  • Create list definitions
  • Create list Instances
  • Rewire Lookups using a PS script

Not only all this, but we started to touch upon the Event receiver, and in this post that's what we're going to focus on. Lookup columns are great, they're just a pain in the arse with the whole rewire business; if only there was a way to automate the process. One guess at what we're about to do.

If you guessed share my secrete recipe for sweet potatoes, you could be more wrong. We are going to automate a lookup field rewire using the feature receiver.

First thing's first open up your project from my previous post and add an event receiver to your Lookup.Date feature. To do this, right click on the feature and select "Add Event Receiver"

with the Event Receiver added your solution explorer should look like
Now When you open your Lookup.EventReceiver.cs file you should see:
At the bottom of your Event Receiver add the following function
/// <summary>
/// Function used to rewire lookup fields
/// </summary>
/// <param name="ConsumerWeb">The web where the list that will be using the source resides</param>
/// <param name="ProvidorWeb">The web where the source list resides</param>
/// <param name="lookupFieldName">The display name of the lookup filed in the consumer</param>
/// <param name="ConsumerListName">The display name of the list that is using the lookup field</param>
/// <param name="ProvidorListName">The display name of the list that is supplying the data to be looked up</param>
public static void UpdateLookupField(SPWeb ConsumerWeb, SPWeb ProvidorWeb, string lookupFieldName, string ConsumerListName, string ProvidorListName)
        SPList consumerList = ConsumerWeb.Lists[ConsumerListName];
        SPList providorList = ProvidorWeb.Lists[ProvidorListName];
        SPFieldLookup field = (SPFieldLookup)consumerList.Fields[lookupFieldName];
        field.SchemaXml = field.SchemaXml.Replace(field.LookupWebId.ToString(), ProvidorWeb.ID.ToString());
        field.SchemaXml = field.SchemaXml.Replace(field.LookupList.ToString(), providorList.ID.ToString());

with your rewire function added, the next step is to re comment the FeatureActivated function. once that's re-commented add the following code, but make sure to sub in your sites url and port number.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
    SPWeb web = properties.Feature.Parent as SPWeb;
    using (SPSite site = new SPSite(web.Site.ID))
        using (SPWeb providorWeb = site.RootWeb)
            SPWeb ConsumerWeb = providorWeb.Webs["hr"].Webs["JobPosting"];
            UpdateLookupField(ConsumerWeb, providorWeb, "Department""Job Posting""Job Posting Departments");

and that's it when you deploy your project your look up fields will automatically rewire.