Add related media custom field to content items

For each content item you create, for example NewsItem, there are default fields, such as author and title. You can add custom media fields that extend the information that the content item holds, for example, an image. Thus, you can relate other content items to the NewsItem via the related media custom field. 

In the following example, you add programmatically the Image custom field as related media to the NewsItem content item: 

In the AddRelatedMediaFieldToContext method above, you:

  1. Specify:
    1. Full name of the content type to which you add a media custom field. In this example, the content type isNewsItem.
    2. Second parameter as a Dictionary collection of related fields.
      The Dictionary collection stores the related media fields, thus associating the custom field name to the related media field object.
  2. Create an instance of the CustomFieldsContext class and pass the content type as a parameter.
  3. Create an instance of the WcfField class to add information about the field, its database mapping, and definition.
  4. Set the following properties of the WcfField class:
  • Name
    Gets or sets the name of the field. The value must not contain spaces or any special characters.
  • ContentType
    Gets or sets the type of the content the field belongs to.
  • FieldTypeKey
    Gets or sets the UserFriendlyDataType value for the field. The class represents an enumeration. In this example, you set the value to RelatedMedia.
  • IsCustom
    Indicates whether the field is a custom field.
  • Definition
    Gets or sets a field definition. Create an instance of the WcfFieldDefinition class. This class wraps the information about the field definition. The definition specifies the way the field is represented in the user interface. Set the following properties of the WcfFieldDefinition class:
    • Title
      Gets or sets the display title of the field.
    • FieldName
      Gets or sets the name of the field. The value must not contain spaces or any special characters.
    • FieldType
      Gets or sets the field control type that is used to represent the field in user interface.
    • AllowMultipleSelection
      Gets or sets whether the control supports multiple selection.
    • FrontendWidgetTypeName
      Gets or sets the type name of the frontend widget.
    • RelatedDataProvider
      Gets or sets the provider of the related data.
    • RelatedDataType
      Gets or sets the type of the related media. In this example, you specify the type as Image.
  • Add the created custom field to the CustomFieldContext instance using AddOrUpdateCustomFields method.
  • Save the context to the database and restart the Sitefinity CMS application.
  • Want to learn more?

    Sign up for our free beginner training. Boost your credentials through advanced courses and certification.
    Register for Sitefinity training and certification.

    Was this article helpful?