다음을 통해 공유


How to: Reference a Column in a Content Type

Applies to: SharePoint Foundation 2010

Columns are never defined directly in a content type. They are defined elsewhere and referenced in the content type. You reference a column in a content type for two reasons:

  • You want to add a column to the content type.

  • You want to change characteristics of a column that the content type inherits from its parent content type.

    For more information about inheritance, see the description of the Inherits attribute of the ContentType element in the content type definition schema.

In declarative XML, you reference a column by using the FieldRef element. In code, you do the same thing by creating an SPFieldLink object.

Note

In Microsoft SharePoint Foundation, fields are columns by another name. Often the word "column" is used when talking about how a field is represented by the user interface.

For information about differences between columns and references to columns, see Fields and Field References.

Referencing Columns by Using Declarative XML

One way to create a content type is to use declarative XML to define the content type in the element manifest file for a Feature. When the Feature is activated, the content type is created. For more information, see Content Type Definitions.

Your content type definition can include a column by referencing it in a FieldRef element. The referenced column can be one that already exists as a site column, or it can be a new column that is created by the same Feature that creates the content type. You can also use the FieldRef element to reference a column that the content type inherits from its parent content type. In this case, your reason for referencing the column would not be to add the column but to change some of its characteristics when it is used in the content type.

To create a column reference by using declarative XML

  1. In the content type definition, add a FieldRef element in the FieldRefs node.

  2. Reference the column by setting the value of the ID attribute of the FieldRef element to the column's ID.

    The value must be the string representation of a GUID enclosed in braces, as in the following example:

    ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}"

    The ID attribute is case-sensitive, so be sure to set the attribute to exactly the same value as the ID attribute of the Field element.

    You can find the IDs for built-in columns in the fieldswss.xml file, which is located on the following path: %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURES\fields.

  3. Set the value of the Name attribute of the FieldRef element to the same value as the Name attribute for the Field element that represents the column.

  4. To define the column as you want, set other attributes of the FieldRef element.

    For example, to change the text that is displayed for the column, set the value of the DisplayName attribute.

Many attributes on the FieldRef element have the same name and purpose as attributes on the referenced Field element. Only the value of the ID attribute and Name attributes are required to be the same. For other attributes, using a different value on the FieldRef element can change characteristics of the column when it is used in the content type without changing the referenced column itself.

Important

The ID, Name, DisplayName, and Required attributes on the FieldRef element are always required, even when the FieldRef element references a field that is defined in the same element manifest.

Example

The following example shows the element manifest for a Feature that creates three site columns and two site content types. The first content type, Financial Document, is a child of the built-in Document content type.

The definition for Financial Document references two of the new site columns, DateOpened and Amount. The FieldRef element that references the DateOpened column sets the DisplayName attribute so that the column name renders as "Date" rather than "Date Opened" as defined in the site column.

The definition for Purchase Order references the third new site column, CostCenter, and sets the DisplayName attribute so that the column name renders as "Department" rather than "Cost Center" as it is defined in the site column.

Purchase Order inherits the column references from its parent, Financial Document, so you do not have to reference them again. The content type also inherits a reference to the Title column from Financial Document, which inherits the column from its parent, Document. The Purchase Order type includes a FieldRef element for the Title column to override the inherited DisplayName attribute with a value of its own.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="https://schemas.microsoft.com/sharepoint/">

  <!-- New Site Columns -->

  <Field ID="{1511BF28-A787-4061-B2E1-71F64CC93FD5}"
         Name="DateOpened"
         DisplayName="Date Opened"
         Type="DateTime"
         Format="DateOnly"
         Required="FALSE"
         Group="Financial Columns">
    <Default>[today]</Default>
  </Field>

  <Field ID="{060E50AC-E9C1-4D3C-B1F9-DE0BCAC300F6}"
         Name="Amount"
         DisplayName="Amount"
         Type="Currency"
         Decimals="2"
         Min="0"
         Required="FALSE"
         Group="Financial Columns" />

  <Field ID="{943E7530-5E2B-4C02-8259-CCD93A9ECB18}"
         Name="CostCenter"
         DisplayName="Cost Center"
         Type="Choice"
         Required="FALSE"
         Group="Financial Columns">
    <CHOICES>
      <CHOICE>Administration</CHOICE>
      <CHOICE>Information</CHOICE>
      <CHOICE>Facilities</CHOICE>
      <CHOICE>Operations</CHOICE>
      <CHOICE>Sales</CHOICE>
      <CHOICE>Marketing</CHOICE>
    </CHOICES>
  </Field>

  <!-- Site Content Types -->

  <!-- Parent ContentType: Document (0x0101) -->
  <ContentType ID="0x0101000728167cd9c94899925ba69c4af6743e"
               Name="Financial Document"
               Group="Financial Content Types"
               Description="Base financial content type"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{1511BF28-A787-4061-B2E1-71F64CC93FD5}" Name="DateOpened" DisplayName="Date" Required="TRUE"/>
      <FieldRef ID="{060E50AC-E9C1-4D3C-B1F9-DE0BCAC300F6}" Name="Amount" DisplayName="Amount" Required="FALSE"/>
    </FieldRefs>
  </ContentType>

  <!-- Parent ContentType: Financial Document -->
  <ContentType ID="0x0101000728167cd9c94899925ba69c4af6743e01"
               Name="Purchase Order"
               Group="Financial Content Types"
               Description="Used for creating purchase orders"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" DisplayName="Item" Required="TRUE" Sealed="TRUE"/>
      <FieldRef ID="{943E7530-5E2B-4C02-8259-CCD93A9ECB18}" Name="CostCenter" DisplayName="Department" Required="TRUE"/>
    </FieldRefs>
  </ContentType>

</Elements>

Referencing Columns in Code

As an alternative to using declarative XML to create a content type, you can create the content type in the FeatureActivated method of a subclass of the SPFeatureReceiver class. The code that creates the content type can include an existing site or list column, or a new column created by the same code that creates the content type, by referencing the column with an SPFieldLink object. As is the case with declarative XML, you might also want to reference a column that is inherited by your content type to change its characteristics in the content type.

There are also other situations in which you might use code to reference a column in a content type. For example, you might want to upgrade an existing content type by adding or removing column references. Or you might want to create a list from a list definition and then modify a content type on the list by adding or removing columns. Whatever your purpose, the approach to using the SharePoint Foundation object model to reference a column is essentially the same.

To create a column reference in code

  1. Get a reference to the SPField object that represents the field that you want to reference.

    You can retrieve the SPField object from the collection held in the Fields property of the SPWeb object that represents the site.

  2. Create an SPFieldLink object to represent the column reference by passing the SPField object to the SPFieldLink constructor.

  3. Get a reference to an SPContentType object.

    If you are creating a new content type, you can use the object that is returned by the SPContentType class constructor. If you are modifying an existing content type, you can retrieve an SPContentType object from the collection that is held in the ContentTypes property of an SPWeb object or an SPList object.

  4. Use the FieldLinks property to access the collection of column references in the SPContentType object. This property returns an SPFieldLinkCollection object.

    Note

    The SPContentType object also has a Fields property that returns an SPFieldCollection object. You cannot add columns directly to this collection. When you add an SPFieldLink object to the FieldLinks collection, a corresponding SPField object is added automatically to the Fields collection. Each SPField object in this collection represents a "merged view" of the base column definition and any overwritten properties that are specified in the column reference.

  5. Add the column reference to the content type by passing the SPFieldLink object to the Add method of the SPFieldLinkCollection object.

Example

The following example shows the FeatureActivated method for a class derived from the SPFeatureReceiver class. When the Feature is activated, code in the FeatureActivated method creates three site columns and adds them to the site column collection on the current site. Then the code creates a content type, Financial Document, and adds it to the content type collection on the current site. The Financial Document content type references two of the new site columns, DateOpened and Amount. Next, the code creates a second content type, Purchase Order, which inherits from Financial Document. The Purchase Order content type references an inherited site column, Title, to change some of its properties in the content type. In addition, the Purchase Order content type includes reference to one of the new site columns, CostCenter.

The example is written as if the feature receiver were part of a Feature scoped at the site collection level. This means that the Feature property returns an SPFeature object that has a Parent property that contains a boxed SPSite object. You should not dispose of this object in your FeatureActivated method. However, any SPWeb object that your code creates must be properly disposed of, as it is in this example.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite siteCollection = (SPSite)properties.Feature.Parent;
    SPWeb site = siteCollection.RootWeb;

    /* CREATE SITE COLUMNS */

    string columnGroup = "Financial Columns";

    // Amount
    string amountFieldName = site.Fields.Add("Amount", SPFieldType.Currency, false);
    SPFieldCurrency amountField = (SPFieldCurrency)site.Fields.GetFieldByInternalName(amountFieldName);
    amountField.Group = columnGroup;
    amountField.DisplayFormat = SPNumberFormatTypes.TwoDecimals;
    amountField.MinimumValue = 0;
    amountField.Update();

    // Date Opened
    string dateOpenedFieldName = site.Fields.Add("Date Opened", SPFieldType.DateTime, false);
    SPFieldDateTime dateOpenedField = (SPFieldDateTime)site.Fields.GetFieldByInternalName(dateOpenedFieldName);
    dateOpenedField.Group = columnGroup;
    dateOpenedField.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
    dateOpenedField.DefaultValue = "[today]";
    dateOpenedField.Update();

    // Cost Center Name
    string costCenterFieldName = site.Fields.Add("Cost Center", SPFieldType.Choice, false);
    SPFieldChoice costCenterField = (SPFieldChoice)site.Fields.GetFieldByInternalName(costCenterFieldName);
    costCenterField.Choices.Add("Administration");
    costCenterField.Choices.Add("Information Services");
    costCenterField.Choices.Add("Facilities");
    costCenterField.Choices.Add("Operations");
    costCenterField.Choices.Add("Sales");
    costCenterField.Choices.Add("Marketing");
    costCenterField.Group = columnGroup;
    costCenterField.Update();

    /* CREATE SITE CONTENT TYPES */

    string contentTypeGroup = "Financial Content Types";

    // Get a content type to be the parent of a new Financial Document content type.
    SPContentType documentCType = site.AvailableContentTypes[SPBuiltInContentTypeId.Document];

    // Create the Financial Document content type.
    SPContentType financialDocumentCType = new SPContentType(documentCType, site.ContentTypes, "Financial Document");
    site.ContentTypes.Add(financialDocumentCType);

    // Note: A content type is not initialized until after it is added.
    financialDocumentCType = site.ContentTypes[financialDocumentCType.Id];
    financialDocumentCType.Group = contentTypeGroup;

    // Add the Date Opened column. Child content types inherit the column.
    SPFieldLink dateOpenedFieldRef = new SPFieldLink(dateOpenedField);
    dateOpenedFieldRef.Required = true;
    financialDocumentCType.FieldLinks.Add(dateOpenedFieldRef);

    // Add the Amount column. Child content types inherit the column.
    SPFieldLink amountFieldRef = new SPFieldLink(amountField);
    financialDocumentCType.FieldLinks.Add(amountFieldRef);

    // Commit changes.
    financialDocumentCType.Update();

    // Create the Purchase Order content type.
    SPContentType purchaseOrderCType = new SPContentType(financialDocumentCType, site.ContentTypes, "Purchase Order");
    site.ContentTypes.Add(purchaseOrderCType);
    purchaseOrderCType = site.ContentTypes[purchaseOrderCType.Id];
    purchaseOrderCType.Group = contentTypeGroup;

    // Modify the Title column inherited from the parent.
    SPFieldLink itemFieldRef = purchaseOrderCType.FieldLinks[SPBuiltInFieldId.Title];
    itemFieldRef.DisplayName = "Item";
    itemFieldRef.Required = true;

    // Add the Department column.
    SPFieldLink departmentFieldRef = new SPFieldLink(costCenterField);
    departmentFieldRef.DisplayName = "Department";
    departmentFieldRef.Required = true;
    purchaseOrderCType.FieldLinks.Add(departmentFieldRef);

    // Commit changes.
    purchaseOrderCType.Update();

}
Public Overrides Sub FeatureActivated(ByVal properties As SPFeatureReceiverProperties)
    Dim siteCollection As SPSite = DirectCast(properties.Feature.Parent, SPSite)
    Dim site As SPWeb = siteCollection.RootWeb
    
    ' CREATE SITE COLUMNS 

    Dim columnGroup As String = "Financial Columns"
    
    ' Amount
    Dim amountFieldName As String = site.Fields.Add("Amount", SPFieldType.Currency, False)
    Dim amountField As SPFieldCurrency = DirectCast(site.Fields.GetFieldByInternalName(amountFieldName), SPFieldCurrency)
    amountField.Group = columnGroup
    amountField.DisplayFormat = SPNumberFormatTypes.TwoDecimals
    amountField.MinimumValue = 0
    amountField.Update()
    
    ' Date Opened
    Dim dateOpenedFieldName As String = site.Fields.Add("Date Opened", SPFieldType.DateTime, False)
    Dim dateOpenedField As SPFieldDateTime = DirectCast(site.Fields.GetFieldByInternalName(dateOpenedFieldName), SPFieldDateTime)
    dateOpenedField.Group = columnGroup
    dateOpenedField.DisplayFormat = SPDateTimeFieldFormatType.DateOnly
    dateOpenedField.DefaultValue = "[today]"
    dateOpenedField.Update()
    
    ' Cost Center Name
    Dim costCenterFieldName As String = site.Fields.Add("Cost Center", SPFieldType.Choice, False)
    Dim costCenterField As SPFieldChoice = DirectCast(site.Fields.GetFieldByInternalName(costCenterFieldName), SPFieldChoice)
    costCenterField.Choices.Add("Administration")
    costCenterField.Choices.Add("Information Services")
    costCenterField.Choices.Add("Facilities")
    costCenterField.Choices.Add("Operations")
    costCenterField.Choices.Add("Sales")
    costCenterField.Choices.Add("Marketing")
    costCenterField.Group = columnGroup
    costCenterField.Update()
    
    ' CREATE SITE CONTENT TYPES 
    
    Dim contentTypeGroup As String = "Financial Content Types"
    
    ' Get a content type to be the parent of a new Financial Document content type.
    Dim documentCType As SPContentType = site.AvailableContentTypes(SPBuiltInContentTypeId.Document)
    
    ' Create the Financial Document content type.
    Dim financialDocumentCType As New SPContentType(documentCType, site.ContentTypes, "Financial Document")
    site.ContentTypes.Add(financialDocumentCType)
    
    ' Note: A content type is not initialized until after it is added.
    financialDocumentCType = site.ContentTypes(financialDocumentCType.Id)
    financialDocumentCType.Group = contentTypeGroup
    
    ' Add the Date Opened column. Child content types inherit the column.
    Dim dateOpenedFieldRef As New SPFieldLink(dateOpenedField)
    dateOpenedFieldRef.Required = True
    financialDocumentCType.FieldLinks.Add(dateOpenedFieldRef)
    
    ' Add the Amount column. Child content types inherit the column.
    Dim amountFieldRef As New SPFieldLink(amountField)
    financialDocumentCType.FieldLinks.Add(amountFieldRef)
    
    ' Commit changes.
    financialDocumentCType.Update()
    
    ' Create the Purchase Order content type.
    Dim purchaseOrderCType As New SPContentType(financialDocumentCType, site.ContentTypes, "Purchase Order")
    site.ContentTypes.Add(purchaseOrderCType)
    purchaseOrderCType = site.ContentTypes(purchaseOrderCType.Id)
    purchaseOrderCType.Group = contentTypeGroup
    
    ' Modify the Title column inherited from the parent.
    Dim itemFieldRef As SPFieldLink = purchaseOrderCType.FieldLinks(SPBuiltInFieldId.Title)
    itemFieldRef.DisplayName = "Item"
    itemFieldRef.Required = True
    
    ' Add the Department column.
    Dim departmentFieldRef As New SPFieldLink(costCenterField)
    departmentFieldRef.DisplayName = "Department"
    departmentFieldRef.Required = True
    purchaseOrderCType.FieldLinks.Add(departmentFieldRef)
    
    ' Commit changes.
    purchaseOrderCType.Update()
    
End Sub

See Also

Tasks

How to: Add a Column to a Site

Reference

FieldRef Element (ContentType)

Concepts

Fields and Field References

Introduction to Columns