Share via


SPFieldLink class

Representa uma referência de coluna simples (também conhecido como campo) que está incluída em um tipo de conteúdo.

Inheritance hierarchy

System.Object
  Microsoft.SharePoint.SPFieldLink

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Syntax

'Declaração
Public Class SPFieldLink
'Uso
Dim instance As SPFieldLink
public class SPFieldLink

Comentários

Se você deseja rastrear determinados metadados de item em um tipo de conteúdo, você pode fazer referência a uma coluna que representa os metadados. No entanto, você não pode criar uma coluna em um tipo de conteúdo; Você deve criar a coluna separadamente e fazer referência na definição de tipo de conteúdo. Como resultado, quando você adiciona uma coluna ao tipo de conteúdo, o tipo de conteúdo contém uma referência para a coluna (ou campo), em vez de coluna (ou campo) em si.

A referência contém um subconjunto das propriedades da definição de campo completo. Essas são as propriedades que você pode personalizar para a coluna conforme ela existe no tipo de conteúdo.

For more information, see Fields and Field References.

O objeto SPContentType contém um SPFieldLinkCollection e um objeto SPFieldCollection .

O objeto SPFieldCollection fornece uma exibição combinada de atributos de uma coluna, conforme elas existirem no tipo de conteúdo especificado. Cada objeto de SPField representa todos os atributos de uma definição de coluna ou campo, combinado com esses atributos que foram substituídos na referência do campo para esse tipo de conteúdo.

Quando você acessa um objeto de SPField em um tipo de conteúdo, SharePoint Foundation combina a definição de campo com a referência de campo e retorna o objeto SPField resultante. Isso é útil porque você não precisa procurar uma definição de campo e todos os atributos na definição de campo são substituídos pela referência de campo para esse tipo de conteúdo.

Não há uma correlação de 1-para-1 entre os itens nos objetos SPFieldLinkCollection e SPFieldCollection . Para cada objeto SPFieldLink que você adicionar a um tipo de conteúdo, SharePoint Foundation adiciona um objeto SPField correspondente que representa o modo de exibição combinado dessa coluna conforme definido no tipo de conteúdo.

Dica

SharePoint Foundation não oferece suporte a herança da classe SPFieldLink .

Examples

O exemplo a seguir mostra um aplicativo de console que cria um tipo de conteúdo, aplica-se a uma lista e adiciona referências a campos no nível do site e uma lista.

Imports System
Imports Microsoft.SharePoint

Module ConsoleApp
    Sub Main()
        Dim site As SPSite = New SPSite("https://localhost")
        Try
            Dim web As SPWeb = site.OpenWeb()
            Try
                Dim contentTypeName As String = "Spec"
                Dim listTitle As String = "Product Specs"
                Dim docType As SPContentType = web.AvailableContentTypes("Document")

                ' Create a content type.
                Dim siteContentType As New SPContentType(docType, _
                                                         web.ContentTypes, contentTypeName)
                ' Add the content type to the site collection.
                siteContentType = web.ContentTypes.Add(siteContentType)

                ' Change the name of the Title field in the content type.
                siteContentType.FieldLinks("Title").DisplayName = "Product"

                ' Add a field to the site field collection.
                Dim siteField As SPField = AddField("Owner", SPFieldType.Text, web.Fields)

                ' Reference the field in the content type.
                AddFieldLink(siteField, siteContentType)
                siteContentType.Update()

                ' Create and configure a document library. 
                Dim listId As Guid = web.Lists.Add(listTitle, _
                                                   "A library of product specifications", _
                                                    SPListTemplateType.DocumentLibrary)
                Dim library As SPDocumentLibrary = CType(web.Lists(listId), SPDocumentLibrary)
                library.OnQuickLaunch = True
                library.ContentTypesEnabled = True
                library.EnableFolderCreation = False 'Hide "Folder" on the New menu
                library.Update()

                ' Add the site content type to the library.
                Dim listContentType As SPContentType = library.ContentTypes.Add(siteContentType)

                ' Add a field to the list field collection.
                Dim listField As SPField = AddField("SKU", SPFieldType.Text, library.Fields)

                ' Reference the field in the list version of the new content type.
                AddFieldLink(listField, listContentType)
                listContentType.Update()

                ' Remove the document content type. 
                Dim id As SPContentTypeId = library.ContentTypes(docType.Name).Id
                library.ContentTypes.Delete(id)
                library.Update()

                ' Review our work.
                Console.WriteLine("Site content type")
                PrintFieldNames(siteContentType)
                Console.WriteLine("List content type")
                PrintFieldNames(listContentType)
            Finally
                web.Dispose()
            End Try
        Finally
            site.Dispose()
        End Try
        Console.Write("Press ENTER to continue...")
        Console.ReadLine()
    End Sub

    Function AddField(ByVal title As String, ByVal type As SPFieldType, _
                      ByRef fields As SPFieldCollection) As SPField
        ' If the field is not in the collection,
        If Not (fields.ContainsField(title)) Then
            ' Add it.
            fields.Add(title, type, False)
        End If
        Return fields.GetField(title)
    End Function

    Sub AddFieldLink(ByRef field As SPField, ByRef contentType As SPContentType)
        ' Is the FieldLink in the collection?
        Dim fieldLink As SPFieldLink = contentType.FieldLinks(field.Id)
        If fieldLink Is Nothing Then ' No, so add it.
            fieldLink = New SPFieldLink(field)
            contentType.FieldLinks.Add(fieldLink)
        End If
    End Sub

    Sub PrintFieldNames(ByVal contentType As SPContentType)
        For Each link As SPFieldLink In contentType.FieldLinks
            Dim field As SPField = contentType.Fields(link.Id)
            ' Screen out system fields.
            If field.Reorderable AndAlso field.InternalName <> "FileLeafRef" Then
                Console.WriteLine("FieldLink.DisplayName = {0}", link.DisplayName)
            End If
        Next link
        Console.WriteLine()
    End Sub
End Module
using System;
using Microsoft.SharePoint;

namespace Test
{
    class ConsoleApp
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("https://localhost"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string contentTypeName = "Spec";
                    string listTitle = "Product Specs";
                    SPContentType docType = web.AvailableContentTypes["Document"];

                    // Create a content type.
                    SPContentType siteContentType = new SPContentType(docType,
                                                                      web.ContentTypes,
                                                                      contentTypeName);
                    // Add the content type to the site collection.
                    siteContentType = web.ContentTypes.Add(siteContentType);

                    // Change the name of the Title field in the content type.
                    siteContentType.FieldLinks["Title"].DisplayName = "Product";

                    // Add a field to the site field collection.
                    SPField siteField = AddField("Owner", SPFieldType.Text, web.Fields);

                    // Reference the field in the content type.
                    AddFieldLink(siteField, siteContentType);
                    siteContentType.Update();

                    // Create and configure a document library. 
                    Guid listId = web.Lists.Add(listTitle,
                                                "A library of product specifications",
                                                 SPListTemplateType.DocumentLibrary);
                    SPDocumentLibrary library = (SPDocumentLibrary)web.Lists[listId];
                    library.OnQuickLaunch = true;
                    library.ContentTypesEnabled = true;
                    library.EnableFolderCreation = false; // Hide "Folder" on the New menu
                    library.Update();

                    // Add the site content type to the library.
                    SPContentType listContentType = library.ContentTypes.Add(siteContentType);
                    library.Update();

                    // Add a field to the list field collection.
                    SPField listField = AddField("SKU", SPFieldType.Text, library.Fields);

                    // Reference the field in the list version of the content type.
                    AddFieldLink(listField, listContentType);
                    listContentType.Update();

                    // Remove the document content type from the library.
                    SPContentTypeId id = library.ContentTypes[docType.Name].Id;
                    library.ContentTypes.Delete(id);
                    library.Update();

                    // Review our work.
                    Console.WriteLine("Site content type");
                    PrintFieldNames(siteContentType);
                    Console.WriteLine("List content type");
                    PrintFieldNames(listContentType);
                }
            }
            Console.Write("Press ENTER to continue...");
            Console.ReadLine();
        }

        static SPField AddField(string title, SPFieldType type, SPFieldCollection fields)
        {
            // If the field is not in the collection,
            if (!fields.ContainsField(title))
            {
                // Add it.
                fields.Add(title, type, false);
            }
            return fields.GetField(title);
        }

        static void AddFieldLink(SPField field, SPContentType contentType)
        {
            // Is the FieldLink in the collection?
            SPFieldLink fieldLink = contentType.FieldLinks[field.Id];
            if (fieldLink == null) // No, so add it.
            {
                fieldLink = new SPFieldLink(field);
                contentType.FieldLinks.Add(fieldLink);
            }
        }

        static void PrintFieldNames(SPContentType contentType)
        {
            foreach (SPFieldLink link in contentType.FieldLinks)
            {
                SPField field = contentType.Fields[link.Id];
                // Screen out system fields.
                if (field.Reorderable && field.InternalName != "FileLeafRef")
                    Console.WriteLine("FieldLink.DisplayName = {0}", link.DisplayName);
            }
            Console.WriteLine();
        }
    }
}

O aplicativo imprime a seguinte saída no console.

Site content type
FieldLink.DisplayName = Product
FieldLink.DisplayName = Owner

List content type
FieldLink.DisplayName = Product
FieldLink.DisplayName = Owner
FieldLink.DisplayName = SKU

Press ENTER to continue...

Thread safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Ver também

Referência

SPFieldLink members

Microsoft.SharePoint namespace

Outros recursos

Fields and Field References

FieldRef Element (ContentType)

Introduction to Columns

Introduction to Content Types