Creating Custom PropertySettings for PropertyMedia
Note
This is for Optimizely CMS 12. For earlier versions, please refer to this page.
In some cases you might need to control the value of a PropertyMedia from code. By declaring a Custom Setting that is applied to one or more properties, an administrator can manually activate the setting in Admin mode. It is also possible to declare Default Settings for PropertyMedia properties that is automatically applied to all instances.
PropertySettings from code for Optimizely CMS 12 or later
Step #1 - Create a custom setting
Start with declaring the settings you need by creating a class for it, like so:
[ServiceConfiguration]
public class Square260Setting : PropertySettings<PropertyMediaSettings> {
public Square260Setting() {
DisplayName = "Square media (260x260)";
}
public override PropertyMediaSettings GetPropertySettings() {
return new PropertyMediaSettings {
Height = 260,
Width = 260,
ResizeMode = ResizeMode.ScaleToFill
};
}
public override Guid ID {
//remember to generate a unique GUID for your class
get { return new Guid("{A772D3D4-921E-4E45-8C8C-6B877A1C59C5}"); }
}
}
This setting, when used, is defining a custom setting that crops an image to 260x260 pixels. Since resize mode is set to ScaleToFill,
the whole area will be filled with content.
If the selected image isn't square, some parts of it will be truncated.
Step #2 - Attach the custom setting to a property
By decorating a Media property with the PropertySettings attribute, you can bind the property to a specific setting, like this:
[Display(GroupName = SystemTabNames.Content, Order = 311)]
[PropertySettings(typeof(Square260Setting))]
public virtual MediaReference Media { get; set; }
Prior to CMS 12 you could inspect the settings in the Admin mode, but this function is missing in CMS 12.
Default settings
Apart from custom settings, it is possible to define a Default setting from code. A default setting, however, will affect every single
instance of PropertyMedia on the site.
The only difference between a custom setting and a default setting is that for default settings, the property IsDefault is
set to true in the constructor of the PropertySettings class.
public Square260DefaultSetting() {
DisplayName = "Square media (260x260)";
IsDefault = true;
}
It is not necessary to attach a default setting to a specific property, it will affect all properties automatically.
If you are looking for a way to attach a default setting to specific properties, please refer to
this blogpost.