Skip to content

Instantly share code, notes, and snippets.

@trnktms
Last active April 6, 2022 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trnktms/cb95b56de81885edb1242057a84096c9 to your computer and use it in GitHub Desktop.
Save trnktms/cb95b56de81885edb1242057a84096c9 to your computer and use it in GitHub Desktop.
public class ProductEntityContentsResolver : RenderingContentsResolver
{
private readonly IProductService _productService;
public ProductEntityContentsResolver(IProductService productService)
{
_productService = productService;
}
protected override Item GetContextItem(Rendering rendering, IRenderingConfiguration renderingConfig)
{
if (!Context.PageMode.IsNormal)
{
// Always return with a default Product item if the page is in edit/preview mode
return _productService.GetFallbackProductEntity();
}
if (Context.Item == null
|| HttpContext.Current?.Request?.Path == null
|| Context.Item.TemplateID.ToString() != Templates.ProductDetailsPage.Id)
{
return Context.Item;
}
var productId = GetProductId(HttpContext.Current.Request.QueryString["item"]);
if (string.IsNullOrEmpty(productId))
{
return Context.Item;
}
var productEntity = _productService.SearchForProductEntity(productId);
if (productEntity == null)
{
return Context.Item;
}
return productEntity;
}
protected override JObject ProcessItem(Item item, Rendering rendering, IRenderingConfiguration renderingConfig)
{
var contextItemJson = base.ProcessItem(item, rendering, renderingConfig);
// Return only dynamic content if no datasource is set
if (string.IsNullOrEmpty(rendering?.DataSource)
|| !ID.TryParse(rendering.DataSource, out ID datasourceId))
return contextItemJson;
var datasourceItem = Context.Database.GetItem(datasourceId);
if (datasourceItem == null) return contextItemJson;
var datasourceItemJson = base.ProcessItem(datasourceItem, rendering, renderingConfig);
if (datasourceItemJson == null) return contextItemJson;
if (contextItemJson != null)
{
contextItemJson.Merge(
datasourceItemJson,
new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union });
return contextItemJson;
}
else
{
// If contextItem is empty, fallback to the datasourceItem
return datasourceItemJson;
}
}
private string GetProductId(string path)
{
var id = path?.Split('/').Last();
return id ?? string.Empty;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment