🔍 Code Extractor

class ContentType

Maturity: 52

Represents a SharePoint content type, which is a named collection of settings and fields that store metadata for items in a SharePoint list.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/contenttypes/content_type.py
Lines:
13 - 280
Complexity:
complex

Purpose

The ContentType class provides a comprehensive interface for managing SharePoint content types. It allows reading and modifying content type properties, managing associated fields and field links, updating content types with propagation to children, reordering fields, and accessing form customization settings. Content types define the structure and behavior of list items in SharePoint, including their metadata fields, document templates, and custom forms.

Source Code

class ContentType(Entity):
    """
    Specifies a content type.

    A named and uniquely identifiable collection of settings and fields that store metadata for individual items
    in a SharePoint list. One or more content types can be associated with a list, which restricts the contents
    to items of those types
    """

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.string_id or str(self.id) or self.entity_type_name

    def reorder_fields(self, field_names):
        """
        The ReorderFields method is called to change the order in which fields appear in a content type.
        :param list[str] field_names: Rearranges the collection of fields in the order in which field internal
             names are specified.
        """
        payload = {"fieldNames": StringCollection(field_names)}
        qry = ServiceOperationQuery(self, "ReorderFields", None, payload)
        self.context.add_query(qry)
        return self

    def update(self, update_children):
        """
        Updates the content type, and any child objects  of the content type if specified,
        with any changes made to the content type.
        :param bool update_children: Specifies whether changes propagate to child objects of the content type.
        """
        super(ContentType, self).update()
        if update_children:
            payload = {"updateChildren": update_children}
            qry = ServiceOperationQuery(self, "Update", None, payload)
            self.context.add_query(qry)
        return self

    @property
    def client_form_custom_formatter(self):
        # type: () -> Optional[str]
        return self.properties.get("ClientFormCustomFormatter", None)

    @property
    def display_form_client_side_component_id(self):
        # type: () -> Optional[str]
        """
        The component ID of an SPFx Form Customizer to connect to this content type for usage with display forms.
        """
        return self.properties.get("DisplayFormClientSideComponentId", None)

    @property
    def display_form_client_side_component_properties(self):
        # type: () -> Optional[str]
        """
        The component properties of an SPFx Form Customizer to connect to this content type for usage with display forms
        """
        return self.properties.get("DisplayFormClientSideComponentProperties", None)

    @property
    def display_form_template_name(self):
        # type: () -> Optional[str]
        """
        Specifies the name of a custom display form template to use for list items that have been assigned
        the content type.
        """
        return self.properties.get("DisplayFormTemplateName", None)

    @property
    def display_form_url(self):
        # type: () -> Optional[str]
        """
        Specifies the URL of a custom display form to use for list items that have been assigned the content type.
        """
        return self.properties.get("DisplayFormUrl", None)

    @property
    def edit_form_client_side_component_id(self):
        # type: () -> Optional[str]
        """
        The component properties of an SPFx Form Customizer to connect to this content type for usage with edit item
            forms
        """
        return self.properties.get("EditFormClientSideComponentId", None)

    @property
    def edit_form_client_side_component_properties(self):
        # type: () -> Optional[str]
        """
        The component ID of an SPFx Form Customizer to connect to this content type for usage with edit item forms
        """
        return self.properties.get("EditFormClientSideComponentProperties", None)

    @property
    def id(self):
        """
        Specifies an identifier for the content type as specified in [MS-WSSTS] section 2.1.2.8.1.
        """
        return self.properties.get("Id", ContentTypeId())

    @property
    def sealed(self):
        # type: () -> Optional[bool]
        """Specifies whether the content type can be changed."""
        return self.properties.get("Sealed", None)

    @property
    def string_id(self):
        # type: () -> Optional[str]
        """A string representation of the value of the Id"""
        return self.properties.get("StringId", None)

    @property
    def name(self):
        # type: () -> Optional[str]
        """Gets the name of the content type."""
        return self.properties.get("Name", None)

    @name.setter
    def name(self, value):
        # type: (str) -> None
        """Sets the name of the content type."""
        self.set_property("Name", value)

    @property
    def new_form_client_side_component_properties(self):
        # type: () -> Optional[str]
        """The component properties of an SPFx Form Customizer to connect to this content type for usage with new
        item forms"""
        return self.properties.get("NewFormClientSideComponentProperties", None)

    @property
    def description(self):
        # type: () -> Optional[str]
        """Gets the description of the content type."""
        return self.properties.get("Description", None)

    @description.setter
    def description(self, value):
        # type: (str) -> None
        """Sets the description of the content type."""
        self.set_property("Description", value)

    @property
    def description_resource(self):
        """Gets the SP.UserResource object (section 3.2.5.333) for the description of this content type"""
        return self.properties.get(
            "DescriptionResource",
            UserResource(
                self.context, ResourcePath("DescriptionResource", self.resource_path)
            ),
        )

    @property
    def document_template(self):
        # type: () -> Optional[str]
        """Specifies the file path to the document template (1) used for a new list item that has been assigned
        the content type.
        """
        return self.properties.get("DocumentTemplate", None)

    @property
    def document_template_url(self):
        # type: () -> Optional[str]
        """Specifies the URL of the document template assigned to the content type."""
        return self.properties.get("DocumentTemplateUrl", None)

    @property
    def edit_form_url(self):
        # type: () -> Optional[str]
        """
        Specifies the URL of a custom edit form to use for list items that have been assigned the content type.
        """
        return self.properties.get("EditFormUrl", None)

    @property
    def group(self):
        # type: () -> Optional[str]
        """Gets the group of the content type."""
        return self.properties.get("Group", None)

    @group.setter
    def group(self, value):
        # type: (str) -> None
        """Sets the group of the content type."""
        self.set_property("Group", value)

    @property
    def hidden(self):
        # type: () -> Optional[bool]
        """Specifies whether the content type is unavailable for creation or usage directly from a user interface."""
        return self.properties.get("Hidden", None)

    @property
    def js_link(self):
        # type: () -> Optional[str]
        """Gets or sets the JSLink for the content type custom form template"""
        return self.properties.get("JSLink", None)

    @property
    def read_only(self):
        # type: () -> Optional[bool]
        """Specifies whether changes to the content type properties are denied."""
        return self.properties.get("ReadOnly", None)

    @property
    def name_resource(self):
        """Specifies the SP.UserResource object for the name of this content type"""
        return self.properties.get(
            "NameResource",
            UserResource(
                self.context, ResourcePath("NameResource", self.resource_path)
            ),
        )

    @property
    def schema_xml(self):
        # type: () -> Optional[str]
        """Specifies the XML schema that represents the content type."""
        return self.properties.get("SchemaXml", None)

    @property
    def fields(self):
        """Gets a value that specifies the collection of fields for the content type."""
        return self.properties.get(
            "Fields",
            FieldCollection(self.context, ResourcePath("Fields", self.resource_path)),
        )

    @property
    def parent(self):
        """Gets the parent content type of the content type."""
        return self.properties.get(
            "Parent",
            ContentType(self.context, ResourcePath("Parent", self.resource_path)),
        )

    @property
    def field_links(self):
        """Specifies the collection of field links for the content type."""
        return self.properties.get(
            "FieldLinks",
            FieldLinkCollection(
                self.context, ResourcePath("FieldLinks", self.resource_path)
            ),
        )

    @property
    def property_ref_name(self):
        return "StringId"

    def get_property(self, name, default_value=None):
        if default_value is None:
            property_mapping = {
                "DescriptionResource": self.description_resource,
                "FieldLinks": self.field_links,
                "NameResource": self.name_resource,
            }
            default_value = property_mapping.get(name, None)
        return super(ContentType, self).get_property(name, default_value)

    def set_property(self, name, value, persist_changes=True):
        super(ContentType, self).set_property(name, value, persist_changes)
        # fallback: create a new resource path
        if name == self.property_ref_name and self._resource_path is None:
            self._resource_path = self.parent_collection.get_by_id(value).resource_path
        return self

Parameters

Name Type Default Kind
bases Entity -

Parameter Details

context: The client context object used for making requests to SharePoint. Inherited from Entity base class.

resource_path: The resource path identifying this content type in the SharePoint API. Inherited from Entity base class.

Return Value

Instantiation returns a ContentType object that represents a SharePoint content type. Methods like reorder_fields() and update() return self for method chaining. Properties return various types including strings (name, description, URLs), booleans (sealed, hidden, read_only), complex objects (ContentTypeId, FieldCollection, FieldLinkCollection, UserResource), or None if not set.

Class Interface

Methods

__init__(context, resource_path)

Purpose: Initializes a ContentType instance (inherited from Entity)

Parameters:

  • context: The client context for SharePoint operations
  • resource_path: The resource path identifying this content type

Returns: ContentType instance

__str__() -> str

Purpose: Returns the string representation of the content type using its name

Returns: The name of the content type

__repr__() -> str

Purpose: Returns a detailed string representation of the content type

Returns: The string_id, id, or entity_type_name of the content type

reorder_fields(field_names: list[str]) -> ContentType

Purpose: Changes the order in which fields appear in the content type

Parameters:

  • field_names: List of field internal names in the desired order

Returns: Self for method chaining

update(update_children: bool) -> ContentType

Purpose: Updates the content type and optionally propagates changes to child objects

Parameters:

  • update_children: Boolean indicating whether changes should propagate to child content types and list items

Returns: Self for method chaining

get_property(name: str, default_value=None) -> Any

Purpose: Gets a property value with special handling for complex properties

Parameters:

  • name: The property name to retrieve
  • default_value: Default value if property is not set

Returns: The property value or default_value

set_property(name: str, value: Any, persist_changes: bool = True) -> ContentType

Purpose: Sets a property value and optionally updates the resource path

Parameters:

  • name: The property name to set
  • value: The value to set
  • persist_changes: Whether to persist changes immediately

Returns: Self for method chaining

@property client_form_custom_formatter() -> Optional[str] property

Purpose: Gets the custom formatter for client forms

Returns: The custom formatter string or None

@property display_form_client_side_component_id() -> Optional[str] property

Purpose: Gets the SPFx Form Customizer component ID for display forms

Returns: The component ID or None

@property display_form_client_side_component_properties() -> Optional[str] property

Purpose: Gets the SPFx Form Customizer component properties for display forms

Returns: The component properties or None

@property display_form_template_name() -> Optional[str] property

Purpose: Gets the name of the custom display form template

Returns: The template name or None

@property display_form_url() -> Optional[str] property

Purpose: Gets the URL of the custom display form

Returns: The form URL or None

@property edit_form_client_side_component_id() -> Optional[str] property

Purpose: Gets the SPFx Form Customizer component ID for edit forms

Returns: The component ID or None

@property edit_form_client_side_component_properties() -> Optional[str] property

Purpose: Gets the SPFx Form Customizer component properties for edit forms

Returns: The component properties or None

@property id() -> ContentTypeId property

Purpose: Gets the identifier for the content type

Returns: ContentTypeId object representing the content type identifier

@property sealed() -> Optional[bool] property

Purpose: Gets whether the content type can be changed

Returns: True if sealed (cannot be changed), False otherwise, or None

@property string_id() -> Optional[str] property

Purpose: Gets a string representation of the content type ID

Returns: The string ID or None

@property name() -> Optional[str] property

Purpose: Gets the name of the content type

Returns: The content type name or None

@name.setter name(value: str) property

Purpose: Sets the name of the content type

Parameters:

  • value: The new name for the content type

Returns: None

@property new_form_client_side_component_properties() -> Optional[str] property

Purpose: Gets the SPFx Form Customizer component properties for new item forms

Returns: The component properties or None

@property description() -> Optional[str] property

Purpose: Gets the description of the content type

Returns: The content type description or None

@description.setter description(value: str) property

Purpose: Sets the description of the content type

Parameters:

  • value: The new description for the content type

Returns: None

@property description_resource() -> UserResource property

Purpose: Gets the UserResource object for the description of this content type

Returns: UserResource object for localized description

@property document_template() -> Optional[str] property

Purpose: Gets the file path to the document template

Returns: The document template file path or None

@property document_template_url() -> Optional[str] property

Purpose: Gets the URL of the document template

Returns: The document template URL or None

@property edit_form_url() -> Optional[str] property

Purpose: Gets the URL of the custom edit form

Returns: The edit form URL or None

@property group() -> Optional[str] property

Purpose: Gets the group of the content type

Returns: The content type group or None

@group.setter group(value: str) property

Purpose: Sets the group of the content type

Parameters:

  • value: The new group for the content type

Returns: None

@property hidden() -> Optional[bool] property

Purpose: Gets whether the content type is hidden from user interfaces

Returns: True if hidden, False otherwise, or None

@property js_link() -> Optional[str] property

Purpose: Gets the JSLink for the content type custom form template

Returns: The JSLink URL or None

@property read_only() -> Optional[bool] property

Purpose: Gets whether changes to content type properties are denied

Returns: True if read-only, False otherwise, or None

@property name_resource() -> UserResource property

Purpose: Gets the UserResource object for the name of this content type

Returns: UserResource object for localized name

@property schema_xml() -> Optional[str] property

Purpose: Gets the XML schema that represents the content type

Returns: The schema XML string or None

@property fields() -> FieldCollection property

Purpose: Gets the collection of fields for the content type

Returns: FieldCollection object containing all fields

@property parent() -> ContentType property

Purpose: Gets the parent content type

Returns: ContentType object representing the parent

@property field_links() -> FieldLinkCollection property

Purpose: Gets the collection of field links for the content type

Returns: FieldLinkCollection object containing all field links

@property property_ref_name() -> str property

Purpose: Gets the property name used for referencing this content type

Returns: The string 'StringId'

Attributes

Name Type Description Scope
context ClientContext The SharePoint client context used for API operations (inherited from Entity) instance
resource_path ResourcePath The resource path identifying this content type in the SharePoint API (inherited from Entity) instance
properties dict Dictionary storing the content type properties retrieved from SharePoint (inherited from Entity) instance
parent_collection EntityCollection Reference to the parent collection containing this content type (inherited from Entity) instance

Dependencies

  • office365.runtime.paths.resource_path
  • office365.runtime.queries.service_operation
  • office365.runtime.types.collections
  • office365.sharepoint.contenttypes.content_type_id
  • office365.sharepoint.contenttypes.fieldlinks.collection
  • office365.sharepoint.entity
  • office365.sharepoint.fields.collection
  • office365.sharepoint.translation.user_resource
  • typing

Required Imports

from office365.sharepoint.contenttypes.content_type import ContentType
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.runtime.types.collections import StringCollection
from office365.sharepoint.contenttypes.content_type_id import ContentTypeId
from office365.sharepoint.contenttypes.fieldlinks.collection import FieldLinkCollection
from office365.sharepoint.entity import Entity
from office365.sharepoint.fields.collection import FieldCollection
from office365.sharepoint.translation.user_resource import UserResource
from typing import Optional

Usage Example

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

# Setup context
site_url = 'https://yourtenant.sharepoint.com/sites/yoursite'
credentials = UserCredential('username', 'password')
ctx = ClientContext(site_url).with_credentials(credentials)

# Get a content type by ID
content_type = ctx.web.content_types.get_by_id('0x0101')
ctx.load(content_type)
ctx.execute_query()

# Access properties
print(f'Name: {content_type.name}')
print(f'Description: {content_type.description}')
print(f'Group: {content_type.group}')
print(f'Is Sealed: {content_type.sealed}')

# Modify content type
content_type.name = 'Updated Content Type'
content_type.description = 'New description'
content_type.update(update_children=True)
ctx.execute_query()

# Reorder fields
field_names = ['Title', 'Description', 'CreatedDate']
content_type.reorder_fields(field_names)
ctx.execute_query()

# Access related collections
fields = content_type.fields
ctx.load(fields)
ctx.execute_query()
for field in fields:
    print(f'Field: {field.internal_name}')

Best Practices

  • Always load the content type using ctx.load() and ctx.execute_query() before accessing properties to ensure data is retrieved from SharePoint
  • Use update(update_children=True) when you want changes to propagate to all child content types and list items
  • Check the 'sealed' property before attempting modifications - sealed content types cannot be changed
  • Check the 'read_only' property before attempting to modify content type properties
  • Use method chaining for multiple operations (e.g., content_type.reorder_fields(...).update(...))
  • Access the fields collection to manage the fields associated with the content type
  • Use field_links to manage field references rather than direct field modifications
  • The string_id property provides a string representation of the content type ID, useful for logging and debugging
  • When setting properties, changes are persisted by default unless persist_changes=False is specified
  • The parent property allows navigation to the parent content type in the inheritance hierarchy

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ChangeContentType 71.8% similar

    A class representing a change event on a SharePoint content type, inheriting from the Change base class.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/changes/content_type.py
  • class ContentTypeEntityData 69.3% similar

    A data class representing SharePoint content type entity metadata, inheriting from ClientValue to provide serialization capabilities for SharePoint API interactions.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/contenttypes/entity_data.py
  • class ContentTypeCreationInformation 68.2% similar

    A data transfer object that encapsulates properties required to create a new SharePoint content type, inheriting from ClientValue for serialization support.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/contenttypes/creation_information.py
  • class ContentTypeCollection 67.1% similar

    Content Type resource collection

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/contenttypes/collection.py
  • class ContentTypeId 64.3% similar

    Represents a SharePoint content type identifier (ID) as a hexadecimal string value that uniquely identifies a content type within a site collection.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/contenttypes/content_type_id.py
← Back to Browse