Reverse-engineer SharePoint fields, content types and list instance—Part3
Posted
by ybbest
on YBBest
See other posts from YBBest
or by ybbest
Published on Fri, 24 Jun 2011 11:43:38 +0000
Indexed on
2011/06/24
16:32 UTC
Read the original article
Hit count: 751
SharePoint 2010
Reverse-engineer SharePoint fields, content types and list instance—Part1
Reverse-engineer SharePoint fields, content types and list instance—Part2
Reverse-engineer SharePoint fields, content types and list instance—Part3
In Part 1 and Part 2 of this series, I demonstrate how to reverse engineer SharePoint fields, content types. In this post I will cover how to include lookup fields in the content type and create list instance using these content types.
Firstly, I will cover how to create list instance and bind the custom content type to the custom list.
1. Create a custom list using list Instance item in visual studio and select custom list.
2. In the feature receiver add the Department content type to Department list and remove the item content type.
C#
AddContentTypeToList(web, “Department”, ” Department”);
private void AddContentTypeToList(SPWeb web,string listName, string contentTypeName)
{
SPList list = web.Lists.TryGetList(listName);
list.OnQuickLaunch = true;
list.ContentTypesEnabled = true;
list.Update();
SPContentType employeeContentType = web.ContentTypes[contentTypeName];
list.ContentTypes.Add(employeeContentType);
list.ContentTypes["Item"].Delete();
list.Update();
}
Next, I will cover how to create the lookup fields. The difference between creating a normal field and lookup fields is that you need to create the lookup fields after the lists are created. This is because the lookup fields references fields from the foreign list.
1. In your solution, you need to create a feature that deploys the list before deploying the lookup fields.
2. You need to write the following code in the feature receiver to add the lookup columns in the ContentType.
C#
//add the lookup fields
SPFieldLookup departmentField = EnsureLookupField(currentWeb, “YBBESTDepartment”, currentWeb.Lists["DepartmentList"].ID, “Title”);
//add to the content types
SPContentType employeeContentType = currentWeb.ContentTypes["Employee"];
//Add the lookup fields as SPFieldLink
employeeContentType.FieldLinks.Add(new SPFieldLink(departmentField));
employeeContentType.Update(true);
private static SPFieldLookup EnsureLookupField(SPWeb currentWeb, String sFieldName, Guid LookupListID, String sLookupField)
{
//add the lookup fields
SPFieldLookup lookupField = null;
try
{
lookupField = currentWeb.Fields[sFieldName] as SPFieldLookup;
}
catch (Exception e)
{
}
if (lookupField == null)
{
currentWeb.Fields.AddLookup(sFieldName, LookupListID, true);
currentWeb.Update();
lookupField = currentWeb.Fields[sFieldName] as SPFieldLookup;
lookupField.LookupField = sLookupField;
lookupField.Group = “YBBEST”;
lookupField.Required = true;
lookupField.Update();
}
return lookupField;
}
© YBBest or respective owner