Repository navigation
Parent property example
VladimirLevchuk edited this page Jun 13, 2013
·
4 revisions
NOTE: example here just shows how to add your own property. The code below is taken from the library code, so it's already implemented.
As an EPiServer site developer I want to have typed access to the parent page in my content pages so I can use it in my logic and easily set from unit tests.
##0. Goal
[ContentType(GUID = "{D45D87F2-E22E-4402-8F6D-7F72559C71F4}")]
public class ArticlePage : ContentPageBase
{
[CmsParent]
public virtual ListPage ParentList { get; internal set; }
}
...
var parentListName = myArticle.ParentList.Greeting;
...
[Test]
void GetArticleViewModel_UsesGreetingFromParentList()
{
var article = new ArticlePage { ParentList = new ListPage { Greeting = "Hello" } };
...
result.Greeting.Should().Be("Hello");
}
##1. Define annotation attribute
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class CmsParentAttribute : Attribute
{}
##2. Define property getter
public class ParentPropertyGetter : IEPiPropertyGetter
{
private readonly IContentLoader _contentLoader;
protected virtual IContentLoader ContentLoader { get { return _contentLoader; } }
public ParentPropertyGetter(IContentLoader contentLoader)
{
// inject content loader here
_contentLoader = contentLoader;
}
public bool CanIntercept(IContentData contentData, PropertyInfo property)
{
// we intercept property if it's declared with any PageData descendant.
return contentData is IContent && property.PropertyType.Is<PageData>();
}
public object GetValue(IContentData contentData, PropertyInfo property)
{
var content = (IContent) contentData;
// the type from the property declaration
var resultType = property.PropertyType;
// load parent page and cast it to the declaration type
var result = ContentLoader.Get<PageData>(content.ParentLink).Cast(resultType);
return result;
}
}
##3. Register our property getter
[InitializableModule]
public class MyInitializationModule : EPiPropertiesInitializationModuleBase
{
public override void ConfigureEPiProperties(EPiPropertiesRegistry registry)
{
registry.For<CmsParentAttribute>().Use<ParentPropertyGetter>();
}
}
##4. Use your new property on a page type
[ContentType(GUID = "{D45D87F2-E22E-4402-8F6D-7F72559C71F4}")]
public class ArticlePage : ContentPageBase
{
[CmsParent]
public virtual ListPage ParentList { get; internal set; }
}