Checking duplicates umbracoUrlName Umbraco 7
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
public class RegisterDuplicateUrlNameDetector : ApplicationEventHandler | |
{ | |
protected override void ApplicationStarting | |
(UmbracoApplicationBase umbracoApplication, | |
ApplicationContext applicationContext) | |
{ | |
ContentService.Publishing += ContentServicePublishing; | |
} | |
static void ContentServicePublishing(IPublishingStrategy sender, | |
PublishEventArgs<IContent> e) | |
{ | |
foreach (var content in e.PublishedEntities){ | |
// get content items UrlName - (more than one content item could be being published, hence the foreach) | |
var contentUrlName = content.HasProperty("umbracoUrlName") && | |
!String.IsNullOrEmpty(content.GetValue<string>("umbracoUrlName")) | |
? content.GetValue<string>("umbracoUrlName") | |
: content.Name; | |
//get sibling content, eg published nodes at the same level in the tree that could contain a clashing url | |
if (content.Parent().Children().Any(f=>f.Id != content.Id && f.Published)) | |
{ | |
foreach (var sibling in content.Parent().Children().Where(f => f.Id != content.Id && f.Published)) | |
{ | |
// get each sibling UrlName | |
var siblingUrlName = sibling.HasProperty("umbracoUrlName") && | |
!String.IsNullOrEmpty(sibling.GetValue<string>("umbracoUrlName")) | |
? sibling.GetValue<string>("umbracoUrlName") | |
: sibling.Name; | |
// check for clash | |
if (siblingUrlName.ToUrlSegment() == contentUrlName.ToUrlSegment()) | |
{ | |
// cancel publishing | |
e.Cancel = true; | |
// bubble up a message to the UI (umbraco 7.3 only) | |
e.Messages.Add(new EventMessage("Save Cancelled", "Clash of UrlNames: " + sibling.Id + "-" + sibling.Name + " and " + content.Id + "-" + content.Name, EventMessageType.Error)); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment