Add related data custom field to content items
For each content item you create, for example BlogPosts, there are default fields, such as author and title. You can add custom fields that extend the information that the content item holds. You can also add a custom field of type Related data, for example, News. Thus, you can relate other content items to the BlogPosts item via the related data custom field.
In the following example, you add programmatically the News custom field as related data to the BlogPosts content item:
In the AddRelatedDataFieldToContext
method above, you:
- Specify:
-
Full name of the content type to which you add the custom field. In the example above, this is the
BlogPost
content item: "Telerik.Sitefinity.Blogs.Model.BlogPost,Telerik.Sitefinity.ContentModules"
- Second parameter as a Dictionary collection of
relatedFields
.
The Dictionary
collection stores the related data fields thus associating the custom field name to the related data field object.
- Create an instance of the
CustomFieldsContext
class and pass the content type as a parameter. - Create an instance of the
WcfField
class to add information about the field, its database mapping, and definition. - 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 RelatedData
. IsCustom
Indicates whether the field is a custom field. Definition
Gets or sets a field definition. You must 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 data. In this example, you specify the type as NewsItem
.
-
Add the created custom field to the
CustomFieldContext
instance using AddOrUpdateCustomFields
method. - Save the context to the database and restart the Sitefinity CMS application.