Skip to content

Instantly share code, notes, and snippets.

@mattbrailsford
Created March 4, 2021 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbrailsford/3125f6d3cf6ac44699709d6dfd5a7d22 to your computer and use it in GitHub Desktop.
Save mattbrailsford/3125f6d3cf6ac44699709d6dfd5a7d22 to your computer and use it in GitHub Desktop.
nuPickers data source to lookup values from a Nest Content property
using nuPickers.Shared.DotNetDataSource;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web;
namespace Outfield.Digital.DataSources
{
public class XPathLookupDataSource : IDotNetDataSource
{
[DotNetDataSource(Title = "Node XPath", Description = "XPath to the node that holds the lookup property")]
public string NodeXPath { get; set; }
[DotNetDataSource(Title = "Lookup Property Alias", Description = "The alias of the lookup property")]
public string LookupPropertyAlias { get; set; }
[DotNetDataSource(Title = "Key Property Alias", Description = "The property alias of the property to use as the key")]
public string KeyPropertyAlias { get; set; }
[DotNetDataSource(Title = "Value Property Alias", Description = "The property alias of the property to use as the value")]
public string ValuePropertyAlias { get; set; }
public IEnumerable<KeyValuePair<string, string>> GetEditorDataItems(int contextId)
{
if (HttpContext.Current != null)
{
var xpath = NodeXPath ?? "$parent";
var currentId = HttpContext.Current.Request.QueryString["currentId"];
var parentId = HttpContext.Current.Request.QueryString["parentId"];
var currentOrParentId = !currentId.IsNullOrWhiteSpace() && currentId != "0" ? currentId : parentId;
var lookups = new Dictionary<string, string>()
{
{ "$current", string.Format("id({0})", currentId) },
{ "$parent", string.Format("id({0})", parentId) },
{ "$ancestorOrSelf", string.Format("id({0})", currentOrParentId) },
{ "$site", string.Format("id({0})/ancestor-or-self::*[@level=1]", currentOrParentId) },
{ "$root", "/root" },
};
foreach (var lookup in lookups)
{
xpath = xpath.Replace(lookup.Key, lookup.Value);
}
var node = UmbracoContext.Current.ContentCache.GetSingleByXPath(xpath);
if (node != null && node.HasValue(LookupPropertyAlias))
{
var deps = node.GetPropertyValue<IEnumerable<IPublishedContent>>(LookupPropertyAlias);
if (deps != null && deps.Any())
{
return deps.ToDictionary(k => KeyPropertyAlias.InvariantEquals("key") ? k.GetKey().ToString() : k.GetPropertyValue<string>(KeyPropertyAlias),
v => ValuePropertyAlias.InvariantEquals("name") ? v.Name : v.GetPropertyValue<string>(ValuePropertyAlias));
}
}
}
return new Dictionary<string, string>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment