Custom FieldType metadata voodoo

When you create a custom field type in Sitecore, often times you want to have access to the context Item on which the field is currently being displayed. Or even more tricky, perhaps you want to know the Field ID or Source that your custom field is displaying. By default/design, field types are left in the dark about this kind of metadata. Sitecore just passes the field type code the value from that field for display and then grabs the value back upon saving.

Well, in typical ‘Field of Dreams’ fashion, “if you build it, they will come”…

It turns out that if you simply add a public property to your custom field type class (such as ItemID), that property will get set by Sitecore. VOODOO!!

Well, really its the work of Sitecore.Shell.Applications.ContentEditor.EditorFormatter class in Sitecore.Client.dll. Specifically, if you look at the SetProperties method, you can see that Sitecore will set any of the properties shown if they are available using reflection. Cool.

 


public static void SetProperties(System.Web.UI.Control editor, Editor.Field field, bool readOnly)
{
Assert.ArgumentNotNull(editor, "editor");
Assert.ArgumentNotNull(field, "field");
ReflectionUtil.SetProperty(editor, "ID", field.ControlID);
ReflectionUtil.SetProperty(editor, "ItemID", field.ItemField.Item.ID.ToString());
ReflectionUtil.SetProperty(editor, "ItemVersion", field.ItemField.Item.Version.ToString());
ReflectionUtil.SetProperty(editor, "ItemLanguage", field.ItemField.Item.Language.ToString());
ReflectionUtil.SetProperty(editor, "FieldID", field.ItemField.ID.ToString());
ReflectionUtil.SetProperty(editor, "Source", field.ItemField.Source);
ReflectionUtil.SetProperty(editor, "ReadOnly", readOnly);
ReflectionUtil.SetProperty(editor, "Disabled", readOnly);
}

In addition, specifying a public “Value” property gets you the field value. But most samples, documentation out there already have that bit.

Happy coding!

Advertisements

About Paul Martin

I enjoy rock climbing, playing guitar, writing code...
This entry was posted in Field Editor, Field Types, Sitecore. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s