Required Lookup
Today I had a requirement to make a lookup field required and set the default value. For a lookup field this isn’t possible within the SharePoint 2010 interface.
My solution
Programmatically the SPFieldLookup also doesn’t have the options available. However casting the Lookup to an SPField does the trick.
public overridevoid FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWeb web = (SPWeb)properties.Feature.Parent;
SPList list = web.Lists["MyList"];
SPField lookup = (SPField)list.Fields["My Lookup"];
lookup.DefaultValue = "1;#Value 1";
lookup.Required = true;
lookup.Update();
}
catch(Exception Ex)
{
// do what ever you want
}
}
Where do I place this? We have a user that is asking for this requirement
Hi Adrian,
You would need to do this in a feature receiver. So you will need to Create a new feature in Visual Studio and add the code in this post to the FeatureActivated method.
Are you happy using Visual Studio or is this something you need help with?
Pieter
I’ll try with VS, I was hoping for a non-deploy solution. Such as one that could be placed in a CEWP
I guess it is just as easy to use PowerShell.
How about something like this:
web = Get-SPWeb $webUrl
list = web.Lists.TryGetList("MyList")
lookup = [Microsoft.SharePoint.SPField]list.Fields["My Lookup"]
lookup.DefaultValue = "1;#Value 1"
lookup.Required = true
lookup.Update()
I didn’t test the above code but it should be ok.