Created
May 22, 2014 13:34
-
-
Save tomfulton/098ae562a624f6af2d05 to your computer and use it in GitHub Desktop.
"Auto Relations" for MNTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Umbraco.Core.Models; | |
using Umbraco.Core.Services; | |
using Umbraco.Web; | |
namespace Client.Umbraco.Extensions.Events | |
{ | |
public class TrackUsages | |
{ | |
public static void HandleSave(IContentService sender, global::Umbraco.Core.Events.SaveEventArgs<global::Umbraco.Core.Models.IContent> e) | |
{ | |
foreach (var savedNode in e.SavedEntities) | |
{ | |
if (savedNode == null) | |
continue; | |
HandleProperty(savedNode, Constants.Properties.PageAlerts, Constants.RelationTypes.AlertToPage, sender); | |
HandleProperty(savedNode, Constants.Properties.PageCallouts, Constants.RelationTypes.CalloutToPage, sender); | |
} | |
} | |
private static void HandleProperty(IContent savedNode, string propertyAlias, string relationTypeAlias, IContentService contentService) | |
{ | |
if (savedNode.HasProperty(propertyAlias)) | |
{ | |
ClearRelationsForNode(savedNode, relationTypeAlias); | |
AddRelationsForNodeFromCsv(savedNode.GetValue<string>(propertyAlias), relationTypeAlias, savedNode, contentService); | |
} | |
} | |
private static void ClearRelationsForNode(IContent node, string relationTypeAlias) | |
{ | |
var relationService = UmbracoContext.Current.Application.Services.RelationService; | |
var relatedPages = relationService.GetByChild(node, relationTypeAlias); | |
foreach (var relation in relatedPages) | |
{ | |
relationService.Delete(relation); | |
} | |
} | |
private static void AddRelationsForNodeFromCsv(string parentNodeIdsCsv, string relationTypeAlias, IContent childNode, IContentService contentService) | |
{ | |
if (string.IsNullOrEmpty(parentNodeIdsCsv)) | |
return; | |
var relationService = UmbracoContext.Current.Application.Services.RelationService; | |
var parentNodeIds = parentNodeIdsCsv.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); | |
foreach (var parentNodeIdStr in parentNodeIds) | |
{ | |
var parentNodeId = 0; | |
if (int.TryParse(parentNodeIdStr, out parentNodeId)) | |
{ | |
var parentContent = contentService.GetById(parentNodeId); | |
if (parentContent != null) | |
{ | |
relationService.Relate(parentContent, childNode, relationTypeAlias); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment