How To: Create custom content type and list instance in SharePoint 2010 using Visual Studio 2010
There are many blogs and MSDN articles talking about the same topic but I decided to write my own one as I did not get a satisfying explanation of why adding the codes here and there when the articles told me to. I believe what I am trying to achieve here is quite simple and common:
1. Create a content type which is reusable
2. Create a list using the content type created in (1)
3. Changes the default “Title” field’s display name (I will discuss this in a separate post)
Below is the step by step instruction of how to achieve the above tasks and some explanations (to the extends of my knowledge) as why we do it the way described. With Visual Studio 2010, SharePoint developers no longer need to manually create feature and element file, packing the feature into a solution file (wsp) and deploying. All those jobs are now automated by Visual Studio 2010 so we can just focus on our tasks of creating custom content types and list instances.
1. Create a new Visual Studio 2010 project
For the purpose of this demo, we will create a project called “Color” which will hold our color content type and color list using the content type and eventually the feature event receiver will insert some initial list items when the feature was activated.
- in VS2010, click [File] –> [New] –> [Project]
- In the “Installed Template” pane, select [Visual C#] –> [SharePoint] –> 2010
- Make sure [.NET Framework 3.5] is selected as the framework type and click on [List Definition].
- Enter “Color” in the Name field, click OK button
- Enter the URL of the site that this solution/feature will be installed (https://SP2010Demo) and select [Deploy as a farm solution] and click Next button.
- Select [Custom List] in the drop down list as the type for the list definition and ensure the checkbox [Add a list instance for this list definition] is check, then click Finish button. You should see something similar in solution explorer to the below screenshot.
Note:
- ListDefinition1/Elements.xml is where you define your custom content types and list templates.
- ListDefinition1/Schema.xml is where you define the view and fields for that list only and as well as applying the content types that you created in ListDefinition1/Elements.xml.
- ListDefinition1/ListInstance1/Elements.xml is where you define the list instance and apply list template type.
2. Create a custom content type
We will create a Color content type with 3 fields/columns to store the color's name, RGB value and Hex value. Since we used Custom List as the base type for the list definition, we have Title column by default and there is no need to create one. However we do need to rename “Title” to “Color Name” and we will look into that later.
Open ListDefinition1/Elements.xml
To declare the fields, insert the following lines in the <Elements> tag and before <ListTemplate> tag. The IDs were generated using GUID Generator. You can open GUID Generator by going to [Too ls] > [Create GUID] and select format 4.
<Field ID="{168076D8-500B-4572-B2FA-9CC9C4664F4C}" Type="Text" Name="RGBValue" DisplayName="RGB Value" Required="TRUE" Sealed="TRUE"/>
<Field ID="{A97BDC8C-8723-455E-818C-56CE8D63BE19}" Type="Text" Name="HexValue" DisplayName="Hex Value" Required="TRUE" Sealed="TRUE"/>
To declare the content type, insert the following lines after the above lines. ugain, Use GUID Generator for ContentType ID. Notice that we are simply attaching the Fields that we created in step 2 above inside <FieldRefs> tag for them to be included in the content type.
<ContentType ID="0x0100736C62A68F6A408E8D0800B14AF43E0E" Name="Colors" Group="Custom CT" Description="Color content type">
<FieldRefs>
<FieldRef ID="{168076D8-500B-4572-B2FA-9CC9C4664F4C}"/>
<FieldRef ID="{A97BDC8C-8723-455E-818C-56CE8D63BE19}"/>
</FieldRefs>
</ContentType>
Modify <ListTemplate> tag so it looks like below. The value of “Type” is the identifier for the template and needs to be unique within the feature. Normally I choose numbers larger than 10000 for it. I’ve also added DisallowContentTypes=”False”. See ListTemplate Element (List Template) for more detailed explanations.
<ListTemplate
Name="Colors"
Type="10050"
BaseType="0"
OnQuickLaunch="TRUE"
SecurityBits="11"
Sequence="410"
DisallowContentTypes="False"
DisplayName="Color - ListDefinition1"
Description="My List Definition"
Image="/_layouts/images/itgen.png"/>
Now your Elements.xml file should look something like below:
3. Apply custom content type in list definition (Schema.xml)
Open ListDefinition1/Schema.xml
Remove the following 2 <ContentTypeRef> tags from <ContentTypes> tag
<ContentTypeRef ID="0x01">
<FolderTargetName="Item" />
</ContentTypeRef>
<ContentTypeRef ID="0x0120" />
Add the following <ContentTypeRef> tag into <ContentTypes> tag
<ContentTypeRef ID="0x0100736C62A68F6A408E8D0800B14AF43E0E"></ContentTypeRef>
Here is the tricky part, although we have declared the fields RGBValue and HEXValue in the Color content type already, we still need to declare them in the list definition again. This is somehow SharePoint was designed. Please see Difference between declaring fields in content types and in list definition. Insert the following lines within <Fields> tag. Those are exactly the same lines as in the content type Elements.xml file.
<Field ID="{168076D8-500B-4572-B2FA-9CC9C4664F4C}" Type="Text" Name="RGBValue" DisplayName="RGB Value" Required="TRUE" Sealed="TRUE"/>
<Field ID="{A97BDC8C-8723-455E-818C-56CE8D63BE19}" Type="Text" Name="HexValue" DisplayName="Hex Value" Required="TRUE" Sealed="TRUE"/>
Add EnableContentTypes="TRUE" attribute to the <List> tag
Now adding the two fields into list’s default view. Find the <View> tag with BaseViewID=”1'” and change <ViewFields> tag so it looks like
<ViewFields>
<FieldRef Name="LinkTitle"></FieldRef>
<FieldRef Name="RGBValue"></FieldRef>
<FieldRef Name="HexValue"></FieldRef>
</ViewFields>
4. Modify ListInstance1/Elements.xml File
Open ListInstance1/Elements.xml file
Modify the <ListInstance> tag so it looks like below
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="https://schemas.microsoft.com/sharepoint/">
<ListInstance Title="Color"
OnQuickLaunch="TRUE"
TemplateType="10050"
Url="Lists/Colors"
Description="A list for colors">
</ListInstance>
</Elements>Notice that we are telling the list instance to use list template with Type ID 10050.
5. Feature Settings
We will change a few feature properties to make it more sensible
Double click on Features/Feature1
Change the Title field to “Color Demo”. This will be the feature name that you see in site collection features page.
Change the Scope drop down list to “Site”. We want to make this feature available at the site collection level instead of the web.
Right click on Features/Feature1 > Properties. In the Properties window, change the Folder Name to “ColorDemoFeature”
At this point, the feature folder name will be “Color_ColorDemoFeature” under the 14 hive. (14\TEMPLATE\FEATURES). To change this, double click on Features/ColorDemoFeature/ColorDemoFeature.feature. In the Properties window, there is a property called “Deployment Path”. By default, it’s set to
$SharePoint.Project.FileNameWithoutExtension$_$SharePoint.Feature.FileNameWithoutExtension$
As you can see
$SharePoint.Project.FileNameWithoutExtension$ = Color
$SharePoint.Project.FileNameWithoutExtension$ = ColorDemoFeatureYou can play around with this to get your desired feature name sitting in the 14 hive.
6. Deployment
This is where the fun starts. Just one click and VS2010 get it done for you!
Double check that we have the correct deployment settings before we start by clicking on the project name Color. In the Properties window, it should have Site URL property set to https://SP2010Demo and Sandboxed Solution set to FALSE.
Right click on the project name Color, then click Deploy. It will go through the following stages to install the solution and features depends on whether it’s the first time you are doing the deployment.
Build Started …
Deploy Started …
Run Pre-Deployment Command
Recycle IIS Application Pool
Retract Solution
Add Solution
Activate Features
Run Post-Deployment Command
Deploy SucceededYou can open the Output windows (View > Output) to see more details.
References:
- You may download the complete Visual Studio 2010 solution file from HERE
- See How to change default Title field name in the custom content type
- Difference between declaring fields in content types and in list definition
- MSDN article about ListTemplate Element (List Template)
Feel free to send me any comment or question.
Note:
2011-01-18 Updated the solution file. (Removed Post-deployment command line setting I left in the solution)
Comments
- Anonymous
September 08, 2010
The comment has been removed - Anonymous
September 09, 2010
oh man, that's what I'm looking for. Are you are SharePoint master? Thanks a lot! - Anonymous
September 09, 2010
The comment has been removed - Anonymous
November 02, 2010
The comment has been removed - Anonymous
November 02, 2010
The comment has been removed - Anonymous
November 09, 2010
Great post! I have a question. Lets say I would like to build a custom Content Type and upon creating that new Content Type in a document library, it will also create a couple of folders in it. Can it be done using Visual Studio 2010? If yes, would be cool if you can also provide some steps =) Many thanks! - Anonymous
November 25, 2010
I have an Item in a SharePoint list. Is it possible to update this Item after an Column update?Now I have to go to the Column and "Save" it so it will update all list columns based on this site column. (last column option).Thanks! - Anonymous
January 04, 2011
this is what i was looking for..but when i tried to deploy the solution i got this error...Error occurred in deployment step 'Activate Features': Value does not fall within the expected range.Do u have any solution for this?where i did the mistake?? - Anonymous
January 17, 2011
could you please give me advice ..Error 5 Error occurred in deployment step 'Run Post-Deployment Command': The command "c:WarmUpServerStartUp.bat" exited with error code: 3.------ Build started: Project: Color, Configuration: Debug Any CPU ------ Color -> C:MAY_WORKresourcesList and ContentType�412.ColorColorColorbinDebugColor.dll Successfully created package at: C:MAY_WORKresourcesList and ContentType�412.ColorColorColorbinDebugColor.wsp------ Deploy started: Project: Color, Configuration: Debug Any CPU ------Active Deployment Configuration: DefaultRun Pre-Deployment Command: Skipping deployment step because a pre-deployment command is not specified.Recycle IIS Application Pool: Skipping application pool recycle because no matching package on the server was found.Retract Solution: Skipping package retraction because no matching package on the server was found.Add Solution: Adding solution 'Color.wsp'... Deploying solution 'Color.wsp'...Activate Features: Activating feature 'ColorDemoFeature' ...Run Post-Deployment Command:The system cannot find the path specified.Error occurred in deployment step 'Run Post-Deployment Command': The command "c:WarmUpServerStartUp.bat" exited with error code: 3.========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==================== Deploy: 0 succeeded, 1 failed, 0 skipped ========== - Anonymous
January 17, 2011
now i cannot access the http://vm-pphg-sp01:81/_layouts/mngfield.aspx ...pls give me any suggestion - Anonymous
January 17, 2011
The comment has been removed - Anonymous
January 17, 2011
Hi Phat,Normally I would prefer to create folders/list items using Feature Receiver. However creating folder in List Instance is also possible, except when your list is a custom list based on the below blog:www.notesfor.net/.../Deploy-a-Custom-SPList-with-folders-from-onetxml.aspxI haven’t actually tried it yet, but that post should give you enough code example to start with. (or more keywords for your research)Cheers,Allen - Anonymous
August 24, 2011
Hi,How do I generate an ID like: 0x0100736C62A68F6A408E8D0800B14AF43E0EWith GUID Generator, I can only generate IDs in the format {8CA3CF05-0337-4414-ACAF-04BCE31EADAC}Thanks in advance! - Anonymous
August 24, 2011
The comment has been removed - Anonymous
August 24, 2011
The comment has been removed - Anonymous
October 17, 2011
Hi Allan,How do I deploy a custom 'EditForm.aspx' and 'DispForm.aspx'using the ListDefinition Template provided by Visual Studio 2010.By default these forms do not appear in the solution created from this template.But these are available in the Visual Studio 2008 Sharepoint List Definition template.Regards,Abhijith - Anonymous
December 08, 2011
Hi allen,I encountered exactly the same error as "seema khaire".May i know how can it be resolved?Thanks,Sudheer. - Anonymous
December 08, 2011
The comment has been removed - Anonymous
December 20, 2011
hi i am still confused. why we are adding the <Fields> in Schema.xml file though we are referenced the 'Content Type'. i thing the contentype indirectly referncing the fileds in 'Site Columns'.don't you think declaring All fields in <Fields> tag will create a local 'column' instead of site Columns' - Anonymous
April 23, 2012
I've had the "Error occurred in deployment step 'Activate Features'", and I found that aften changing the ListTemplate property Type=10050 back to 10000 as VS2010 sets as default, my project runs again. - Anonymous
May 30, 2012
Good introductory post, although some of the comments posted thus far suggest it can possibly be edited again. There's a technet article that covers a similar topic which may be wirth looking at.If I can find it, I'll post the link. - Anonymous
July 05, 2012
I am trying to create multiple content types for a List where user is able to select the content type when adding a new item. I have done this on a Document library where after uploading an item, you can toggle the content type and see the fields updated on the form before your eyes. The regular list has a selection under the new arrow, but no toggle or showing of content type on the form. Is there any way to do this without custom coding? - Anonymous
August 21, 2012
Thank you! Well written, easy to follow and to the point. - Anonymous
December 12, 2013
Why not we create the list in SharePoint OOB first and then export it as list intance....how about this approach. What is the best approach for installing SharePoint lists??? - Anonymous
December 23, 2013
Thanks a loti tried this and it;s working.i think you can solve the problem by using public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = (SPSite)properties.Feature.Parent; if (site != null) { using (SPWeb web = site.RootWeb) { web.ContentTypes["Your Content Type Name"].Update(); } } } - Anonymous
December 23, 2013
There is very easy solution no need to copy fields in step number 3you said :"Here is the tricky part, although we have declared the fields RGBValue and HEXValue in the Color content type already, we still need to declare them in the list definition again. This is somehow SharePoint was designed. Please see Difference between declaring fields in content types and in list definition. Insert the following lines within <Fields> tag. Those are exactly the same lines as in the content type Elements.xml file."But SharePoint not working like that and you can use this to solve your problem <ContentType ID="ContentTypeId " Group="ContentTypeGroup" Name="ContentTypeName" > <FieldRefs> </FieldRefs> </ContentType> for example <ContentType ID="0x0100fc51e900668d4e3f92c5458f11b6f34202" Group="News" Name="Local News" > <FieldRefs> </FieldRefs> </ContentType> - Anonymous
March 25, 2014
You should create the Content Type in code first, then add a list instance to your project using the Content Type you have just created.This saves lots of time doing unnecessary work adding the fields to the Schema.xml of the list definition!