Skip to content

Instantly share code, notes, and snippets.

@AThraen
Last active November 9, 2022 09:42
Show Gist options
  • Select an option

  • Save AThraen/a289d7cae648a9540a0d7b0035864b7c to your computer and use it in GitHub Desktop.

Select an option

Save AThraen/a289d7cae648a9540a0d7b0035864b7c to your computer and use it in GitHub Desktop.
Optimizely CMS - Property Dependency (one property is dependent on another)
public class DependentPropertyAttribute : Attribute
{
public string DependentProperty { get; set; }
public object Value { get; set; }
public bool Compare(object value)
{
if (value == null)
{
return Value == null;
}
return value.Equals(Value);
}
public DependentPropertyAttribute(string propertyName, object value)
{
DependentProperty = propertyName;
this.Value = value;
}
}
[ModuleDependency(typeof(InitializationModule))]
public class DependentPropertyInitialization : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
var registry = context.Locate.Advanced.GetInstance<MetadataHandlerRegistry>();
registry.RegisterMetadataHandler(typeof(ContentData), new DependentPropertyMetadataExtender());
}
public void Uninitialize(InitializationEngine context) { }
}
public class DependentPropertyMetadataExtender : IMetadataExtender
{
public void ModifyMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
{
if(metadata.Model is IContent)
{
//We have a piece of content. Let's iterate through the properties to see if there are any dependencies
foreach (ExtendedMetadata extendedMetadata in metadata.Properties.OfType<ExtendedMetadata>())
{
var prop = extendedMetadata.Attributes.OfType<DependentPropertyAttribute>().FirstOrDefault();
if(prop!=null)
{
//We have a dependent property. Let's find the property that it depends on
var dp=metadata.Properties.OfType<ExtendedMetadata>().FirstOrDefault(em => em.PropertyName == prop.DependentProperty);
if (dp != null)
{
if (!prop.Compare(dp.InitialValue))
{
//Not same value, don't show!
extendedMetadata.ShowForEdit=false;
}
//Set reload on change
if (!dp.AdditionalValues.ContainsKey((object)"reloadOnChange"))
{
dp.AdditionalValues.Add((object)"reloadOnChange", (object)true);
}
}
}
}
}
}
}
//Example of how to use the dependent properties in a content type.
//Here goes content type declaration typically
public class ProductPage : StandardPage, IHasRelatedContent
{
//...Other properties on content type
[Display(
GroupName = SystemTabNames.Content,
Order = 340)]
public virtual bool ShowSpecialLink { get; set; }
[Display(
GroupName = SystemTabNames.Content,
Order = 350)]
[DependentProperty("ShowSpecialLink", true)]
public virtual Url SpecialLink { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment