Custom Fields

Last Updated: 2018-12-04

If you want to read more about the fields included in Piranha, please refer to Standard Fields.

Fields are the lowest level of content in Piranha CMS and are used to build up Regions and Blocks. In many cases the fields included in Piranha are sufficient, but you might also want to create custom fields for you application. One use case is for example if you would like to reference a custom entity in your application from a Page or Post, much like the included PageField does.

The IField Interface

In order to create a custom field your class has to implement the IField interface from the Piranha.Extend namespace. The interface contains the following methods that needs to be implemented.

GetTitle

string GetTitle()

Gets the list item title if this field is used in a collection region. Please note that it's only supported to reference Field Properties as title.

Init

void Init(...)

Initializes the field for client use. This is called when the field is loaded and is used for loading additional resources. As an example, the ImageField loads the Id of the referenced image from the database, then when Init() is called it loads the referenced media object.

The method supports Dependency Injection which means any service registered in the DI Container can be added as an parameter. This is useful when loading custom data from your application.

Create The Field

Let's take a look at how a simple string field could be implemented.

using Piranha;
using Piranha.Extend;

[FieldType(Name = "Custom String")]
public class CustomStringField : IField
{
public string Value { get; set; }

public string GetTitle() {
return Value;
}

public void Init() {
// Nothing special for this field
}
}

Register The Field

All available fields has to be registered in the singleton Piranha.App after the app has been initialized.

Piranha.App.Init(api);

// Register custom fields
Piranha.App.Fields.Register<CustomStringField>();

Create The Manager View

The manager interface is based on EditorTemplates for each field. All views for fields should be placed in

~/Areas/Manager/Views/Shared/EditorTemplates

with the same name as the field class, in this example it should be named CustomStringField.cshtml.

@model CustomStringField
@Html.TextBoxFor(m => m.Value, new { @class = "form-control" })

Value Serialization

As default, all fields are serialized as JSON in the database, however you can choose to serialize your data in a different way, or maybe even store it in a separate table in the database. The easiest way to do this is the register a custom serializer for your field. You can read more about this in Custom Serializers.