Tuesday, April 19, 2016

OnItemRenaming

public void OnItemRenaming(object sender, EventArgs args)
    {
      Item item = Event.ExtractParameter(args, 0) as Item;

      if (item == null)
      {
        return;
      }

      Helpers helpers = new Helpers();
      Site site = helpers.FindSiteFromItemPath(item.Paths.FullPath);

      string contextPath = site?.Properties[ContextPathAttribute];

      if (string.IsNullOrEmpty(contextPath))
        return;

      int macroPos = contextPath.IndexOf(ContextMacro, StringComparison.Ordinal);
      if (macroPos > -1)
      {
        var rootDataFolderPath = contextPath.Substring(0, macroPos - 1);
        Item datasourceFolder = item.Database.GetItem(rootDataFolderPath);

        if (datasourceFolder == null)
          return;

        if (datasourceFolder.GetChildren().Any())
        {
          string oldName = HttpContext.Current.Items[ItemNamePersistenceKey]?.ToString() ?? string.Empty;
          Item childItemWithSameName = datasourceFolder.Axes.GetDescendants().FirstOrDefault(x => x.Name == oldName);

          if (childItemWithSameName != null)
          {
            using (new SecurityDisabler())
            {
              childItemWithSameName.Editing.BeginEdit();
              childItemWithSameName.Name = item.Name;
              childItemWithSameName.Editing.EndEdit();
            }

            publish renamed item(might take this out)
            Sitecore.Publishing.PublishOptions publishOptions =
            new Sitecore.Publishing.PublishOptions(item.Database,
                                           Database.GetDatabase("web"),
                                           Sitecore.Publishing.PublishMode.SingleItem,
                                           item.Language,
                                           System.DateTime.Now);  // Create a publisher with the publishoptions
            Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions);
            publisher.Options.RootItem = item;

            // Publish children as well?
            publisher.Options.Deep = true;
            publisher.Publish();
          }
        }
      }

    }

No comments:

Post a Comment