ReferenceField

View as Markdown

ReferenceField

ReferenceField describes a reference field in a content type or global field schema, with data_type set to reference. It adds the content types it links to, and its plugins, to the properties of Field.

When to Use This Class: Use this class to link an entry to entries of another content type, for example a blog post to its author.

Conceptual Role: Acts as the Field subclass that the SDK creates for a field with data_type set to reference.

Returns: ReferenceField. A reference field of a schema.

Properties

ReferenceField inherits every property of Field and adds the properties below.

NameTypeRequiredDefaultDescription
ReferenceToJsonElement?NonullUIDs of the content types the field links to. Serialized as reference_to.
PluginsList<string>?NonullUIDs of plugins for the field. Serialized as plugins.

Class-Level Notes

Reference settings.

  • ReferenceTo is a JsonElement, so it carries the value as the API returns it. Create it with JsonSerializer.SerializeToElement(new[] { "author" }).
  • Set FieldMetadata.RefMultiple to true to let the field hold more than one referenced entry. See FieldMetadata.

Method Index

ReferenceField has no methods. Set its properties and add it to ContentModelling.Schema.

Class-Level Snippet

The snippet below creates a content type with a reference field that links one author entry.

using System;
using System.Collections.Generic;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Fields;
using System.Text.Json;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

ContentModelling model = new ContentModelling
{
    Title = "Blog Post",
    Uid = "blog_post",
    Schema = new List<Field>
    {
        new TextboxField { DisplayName = "Title", Uid = "title", DataType = "text", Mandatory = true, Unique = true },
        new ReferenceField
        {
            DisplayName = "Author",
            Uid = "author",
            DataType = "reference",
            ReferenceTo = JsonSerializer.SerializeToElement(new[] { "author" }),
            FieldMetadata = new FieldMetadata { RefMultiple = false }
        }
    }
};

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Create(model);
    Console.WriteLine(response.OpenJsonObjectResponse()["notice"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}