Saturday 17 March 2012

SharePoint: Basics of Site Columns

Site columns are column/field definitions which can be created at site collection level for making them available to reuse at sub-sites or they can also be created at list level which are termed as list columns. One can map them to database columns with reusable capability.

Site columns can be created either declaratively or programmatically.

a.       Declarative manner

In this method, site columns are declared in the element manifest file of the feature as shown below.


Following table contains important details about creating the different type of site columns.

Type of field
Field Type
Further customization tips
Yes/No
Type="Boolean"

Single line of text
Type="Text"

Multiple lines of text
Type="Note"

Plain Text:
RichText="FALSE"

Rich Text:
RichText="TRUE" RichTextMode="Compatible"

Enhanced Rich Text:
RichText="TRUE" RichTextMode="FullHtml"

Use NumLines attribute to set the number of lines to display


Choice (menu to choose from)
Single Choice (dropdown or radio buttons):
Type="Choice"

Multiple choices (check boxes):
Type="MultiChoice"

Dropdown:
Format="Dropdown"

Radio Buttons/ check boxes:
Format="RadioButtons"

Choices can be entered using choice tag and default choice can be set using Default tag as shown below.
<CHOICES>
      <CHOICE>First Choice</CHOICE>
      <CHOICE>Second Choice</CHOICE>
    </CHOICES>
<Default>First Choice</Default>

Use fill in choice option to allow users entering the values apart from fixed choices.
FillInChoice="TRUE"

Date and Time
Type="DateTime"

Date and Time:
Format="DateTime"

Date Only:
Format="DateOnly"

Hyperlink or Picture
Type="URL"

Display as link:
Format="Hyperlink"

Display as image:
Format="Image"

Integer
Type="Integer"


Number
Type="Number"


Person or Group
Single User or Group
Type="User"

Multiple Users or Groups
Type="UserMulti"

Allow all people:
UserSelectionScope="0"

Allow people from specific group:
UserSelectionScope="group id here"

Multiple values:
Mult="TRUE"

Communicator presence:
Presence="TRUE"

Allow people only
UserSelectionMode="0"

Allow both people and groups:
UserSelectionMode="1"


Currency
Type="Currency"

Use LCID attribute to set the currency type of specific locale
Calculated
Type="Calculated"

Use excel formula syntax to calculate the value of this field. FieldRefs to other fields can be used in the same manner as that of excel cell values in excel formula.

<Formula> excel formula </Formula>
<FieldRefs>
      <FieldRef Name="Field1"/>
      <FieldRef Name="Field2"/>
</FieldRefs>


Other important customizations to remember are outlined in the table below. Most of them are independent of field type.

Attribute/ child Tags
Value
Purpose
ID
Registry format GUID
Specifies the GUID of the field contained within braces ({}).
Name

Sets internal name of the field
Static Name

Keep this same as that of internal name
Display Name

Display name of the field
Required
True/ False
Denotes whether field is mandatory or not.
Description

Sets the description to be shown on list forms.
Group

Group name to which column should belong
Hidden
True/ False
If True, then field is not displayed anywhere in user interface.
ReadOnly
True/ False
If True, then field does not get displayed in New/Edit form.
Min
Max
MaxLength
Integer
Minimum and maximum values.
Max length controls length of the column value.
Decimals
Integer
Determines number of decimals to display.
EnforceUniqueValues

Enforces unique values. For column to be unique, it must be indexed also.
Indexed
True/ False
Used for efficient filtering
LinkToItem

True/ False
Specifies whether column should be shown with link  (similar to Edit column)to display form.
ListItemMenu
True/ False
Specifies whether column should be shown with item context menu (similar to LinkTitle column).
ShowInDisplayForm, ShowInEditForm, ShowInNewForm,
ShowInListSettings,
ShowInVersionHistory,
ShowInViewForms
True/ False
Controls visibility of the column on Display form, Edit form, New form, List Settings, Version History and List View form respectively
Validation

This child tag is used for validating the field value using excel based formula.

<Validation Message="Validation failed message" Script="Excel compatible validation formula"/>



Apart from above, there are two more attributes named “Overwrite” and “OverwriteInChildScope”. These must be set to True at least during development phase to avoid errors in case of frequent deployments.
Note here that some of the above attributes are newly added in SharePoint 2010.  They do not exist in WSS 3.0 or MOSS 2007.


Steps to Create site column in declarative fashion

1.       In Visual Studio 2010, click New Project, expand the SharePoint node, click 2010 , and then click Empty SharePoint Project. Name the project as SPCustomDevelopment and then click OK.
2.       In the SharePoint Customization Wizard, select the local SharePoint site that can be used for debugging and and type of deployment method (Sandbox or Farm) as shown in Figure 1. Click Finish.

Figure 1: Select Deployment Method

3.       In Solution Explorer, right-click the Features node and then click Add Feature as shown in Figure 2.

Figure 2: Add Feature

4.       Name the feature as SPCustomDevelopment – Site Columns and give appropriate description. Ensure that the feature scope is set to Site. As Site Column gallery in which the site column gets created is present at root web of Site collection, the scope of the feature creating it must be set to Site as shown in Figure 3.

Figure 3: Name the Feature

5.       Rename the Feature 1 folder to Site Columns as shown in Figure 4 for better readability.

Figure 4 : Rename the Feature Folder

6.       In Solution Explorer, right-click the SPCustomDevelopment project, select Add , and then select New Item as shown in Figure 5.

Figure 5: Add New Item to Project

7.       In the Add New Item dialog box, select the Empty Element template, type Site Columns as the name, and then click Add as shown in Figure 6.

Figure 6: Add an Empty Element Manifest Item

8.       Open the Elements.xml file inside Site Columns project item and then replace the file content with the following code example.


  <Field ID="{6F87C38C-5218-45D8-905E-877D694ECC31}"
         Type="Choice"
         Name="Technology"
         StaticName="Technology"
         Description="Select the technology on which this book is written."
         DisplayName="Technology"
         Format="Dropdown"
         Group="SharePoint 2010 Custom Development"
         Required="TRUE"
         Overwrite="TRUE"
         >
    <CHOICES>
      <CHOICE>C#</CHOICE>
      <CHOICE>ASP.NET</CHOICE>
      <CHOICE>SharePoint 2010</CHOICE>
      <CHOICE>MOSS 2007 and WSS 3.0</CHOICE>
    </CHOICES>
  </Field>
  <Field ID="{52AE411D-32FB-484C-A04F-ED6C7E41A593}"
         Type="Text"
         Name="Publication"
         StaticName="Publication"
         DisplayName="Publication"
         Description="Type the Publication of this book."
         Group="SharePoint 2010 Custom Development"
         Required="TRUE"
         Overwrite="TRUE"/>
  <Field ID="{7D8A68DA-3A2D-444D-A721-1E7A6633402B}"
         Type="Currency"
         Name="PriceOfBook"
         StaticName="PriceOfBook"
         DisplayName="Price"
         Description="Enter the book cost."
         Group="SharePoint 2010 Custom Development"
         Required="TRUE"
         Overwrite="TRUE"/>
  <Field ID="{E93762F1-6F7E-4DFC-9161-0B3B35A7BE35}"
         Type="UserMulti"
         Name="BookAuthors"
         StaticName="BookAuthors"
         DisplayName="Authors"
         Description="Enter the book authors"
         Group="SharePoint 2010 Custom Development"
         Required="TRUE"
         Mult="TRUE"
         UserSelectionMode="0"
         UserSelectionScope="0"
         Overwrite="TRUE"/>
  


9.       Save the file.

    10.   Add the Site Columns project item to Site Columns feature as shown in Figure 7.


Figure 7: Associate Element manifest to Feature


11.   Right click the solution name and then click Deploy as shown in Figure 8. Visual Studio 2010 will build and deploy the solution to the farm/ site collection depending upon the deployment methodology selected in Step 2.

Figure 8: Build and Deploy the solution

12.   VS 2010 will activate the feature Site Columns and custom site columns will be created into the Site Column gallery. Navigate to local site collection=>Site Settings=>Site Column. Filter the columns displayed using Show Group dropdown as shown in figure 9.


Figure 9: Custom site columns present in the Site Column gallery


b.      Programmatic manner

I find this method more error prone and also it becomes difficult to maintain the code in case there is need of creating huge number of site columns. Hence I prefer declarative method rather than going for this. However, for certain type of site columns e.g lookup columns, metadata columns, it becomes mandatory to create them programmatically in certain situations. We will see how to create lookup columns, metadata columns in my later blogs.

The logic is to get the SPFieldCollection object of SPWeb or SPList and then make use of SPFieldCollection.Add and SPFieldCollection.AddFieldAsXml methods to create the field. My personal recommendation is to use later one as it is more powerful e.g. it gives you option to add the new field into all associated content types of list, add new field into the default list view or even adding your own custom attributes. Refer the figure below.

Figure 10: Add Site Columns Programmatically



Site columns Vs List columns

The fields which are stored in Site Column gallery at site collection level are termed as Site Columns. These columns are available for use in entire site collection.
The fields which are created directly in list or once site columns from site column gallery are used in list, then they are termed as List Columns. When existing site column (parent) is added to the list, parent field does not get directly associated with the list. Instead a separate field definition copy is created which derives from its parent field. This separate copy of site column (list column) is associated with list. Hence changes made in List column does not reflect in Site Columns but changes made Site Columns can be reflected in derived list columns in some cases.

In declarative way, the changes in columns through element manifest get reflected in site columns present in site column gallery only. Propagating the site column changes to the list columns can be achieved either by programmatic way or through browser. However doing so, make list columns customized. Once list column is customized, it gets detached from its parent site column and further propagation of changes done through programmatic way or through browser might not work.

Figure 11: Site column change propagation


SharePoint does not support phased deployment for many of its artifacts and site column is one of the them. Rather, I should say it is one of the most painful area in phased deployment. It has given me bad memories in my past…Ohh…I still remember…such a nightmare it was…The problem lies in SharePoint architecture of site columns and list columns. So what to do in case when phased deployment is unavoidable… my take is to create all the site columns and content types required for all the phases in one go and deploy them in first deployment only….and then pray that future phases or change requests won’t need any changes in them….


Key Take Away Points 

1.       The site columns created in declarative manner are kept in Site Column gallery. Hence the feature who creates them must be site collection scoped feature
2.       The changes made in declarative site column definitions are reflected in Site Column gallery only. The list columns inherited from declarative site columns will not reflect the changes.
3.       Site columns do not support phased deployment. Hence create all the site columns required in all phases in first deployment of the application.
4.       Don’t create site columns programmatically…it is error prone and not recommended way…
5.       If you are creating the site columns through browser interface, then do not create the site columns directly in list unless unavoidable (except look up/ metadata columns). First create the site columns in Site Column gallery and then add them to list level. This makes maintenance and support job lot easier.


To end this, will suggest to have a look at an OOB feature “SharePointRoot\TEMPLATE\FEATURES\fields” for reference purpose. It has field definitions of OOB site columns. In addition, you can also take help of magical power of SharePoint Manager 2010 (http://spm.codeplex.com/) to check the field schemas.

Time for a tea break...too hot in office during weekends without AC...can't wait for my laptop so that I can Learn from home...have booked it yesterday in Dell India, Hyderabad. Was not aware that it takes 8 days. :-( 

4 comments:

  1. Yetanother SharepointCustomizer9/12/2012 1:46 am

    really nice article. for my use case, I have to create the field programmatically. how do you obtain the registry format GUIDs? Do you just generate them in VStudio?

    ReplyDelete
    Replies
    1. Glad you liked it. Go to the Tools menu in Visual Studio where you will find Create GUID option using which you can generate registry format GUIDs. Or you can make use System.Guid.NewGuid()to create it in code.

      Delete
  2. very nice article thanks

    Regards,
    Zuri
    zurijackshot@gmail.com

    ReplyDelete
  3. Great post! It's complete and really helpful.

    ReplyDelete