What is the proper way to add a Field to a custom Part in code?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 07:38:54

1) Use placement.info and alternates to customize where you want to render the field

2) You should be able to adjust the settings in Dashboard -> Content Definition -> YourContentType -> Parts -> under the MyPart settings.

You could also attach the field to the type instead (note: it isn't really attached to the type, but to the part with the same name as the type):

Migrations.cs:

ContentDefinitionManager.AlterPartDefinition("MyType", part => part
    .WithField("Image", field => field
        .OfType("MediaLibraryPickerField")
        .WithDisplayName("Image")
        .WithSetting("MediaLibraryFieldSettings.Required", "False")
    )
);

ContentDefinitionManager.AlterTypeDefinition("MyType", type => type
    .WithPart("MyType");

3) You can either use the dynamic notation, or search the field:

// cast to dynamic
var url = ((dynamic)ContentItem).MyPart.Image.FirstMediaUrl

// or search for the field
var field = ContentItem.MyPart.Fields.OfType<MediaLibraryPickerField>().Single(f => f.Name == "Image");
// or ContentItem.MyPart.Fields.Single(f => f.Name == "Image") as MediaLibraryPickerField;
var url = field.FirstMediaUrl;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!