I use Umbraco 7.4.12 And I need to add property to media type dynamically from code and not from the UI.
What the best way to do this?
Something like this should do?
Below I am adding a textstring property to the default Image media type. I even tested it just now, and it's working :-)
There is an overload to the AddPropertyType method which allows you to add the property to a given tab/property group if needed.
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
var dataTypeService = ApplicationContext.Current.Services.DataTypeService;
var mediaType = contentTypeService.GetMediaType(1032);
if (mediaType != null && !mediaType.PropertyTypeExists("myNewPropertyAlias"))
{
var dataTypeDefinitions = dataTypeService.GetAllDataTypeDefinitions().ToArray();
var textStringDataTypeDefinition = dataTypeDefinitions.FirstOrDefault(p => p.Name.ToLower() == "textstring");
mediaType.AddPropertyType(new PropertyType(textStringDataTypeDefinition) { Name = "My New Property Name", Alias = "myNewPropertyAlias" });
contentTypeService.Save(mediaType);
}
}