2017-08-28 62 views
0

我需要以编程方式删除Sitecore中的项目,但是如果它们被其他项目引用,那么我需要更新这些项目以引用其他项目。如何删除Sitecore中的项目并更新所有引用

在UI中,Sitecore为此提供了一个对话框,但item.Delete()item.Recycle()方法似乎没有任何类似的替代方法。我可以使用Sitecore.Globals.LinkDatabase.GetItemReferrers(item, true)来获取引用项目,但我仍然需要从这些项目中获取特定字段并根据其类型进行更新。

回答

0

据我所知,只要项目的ID在引用项目的字段中被替换,该字段的类型应该没有关系。一个例外是富文本字段类型,其中在HTML链接的格式如下:

<a href="-/media/somelowercaseguidwithouthyphens.ashx"></a> 

因此,我们应该可以做两个简单的替代品。一个用于物品ID,另一个用于较小的未加标识的ID。

首先,获取引用项链接,并创建替换字符串。

var links = Sitecore.Globals.LinkDatabase.GetItemReferrers(item, true); 

string oldIdWithoutBraces = item.ID.ToString().Replace("{", "").Replace("}", ""); 
string newIdWithoutBraces = newItem.ID.ToString().Replace("{", "").Replace("}", ""); 
string oldIdForHyperlinks = oldIdWithoutBraces.ToLower().Replace("-", ""); 
string newIdForHyperlinks = newIdWithoutBraces.ToLower().Replace("-", ""); 

然后,对于每个引用项链接,获取其引用字段并更新其中的项ID。

using (new Sitecore.SecurityModel.SecurityDisabler()) 
{ 
    foreach (var link in links) 
    { 
     var sourceItem = link.GetSourceItem(); 
     var fieldId = link.SourceFieldID; 
     var field = sourceItem.Fields[fieldId]; 

     sourceItem.Editing.BeginEdit(); 

     try 
     { 
      field.Value = field.Value 
       .Replace(oldIdWithoutBraces, newIdWithoutBraces) 
       .Replace(oldIdForHyperlinks, newIdForHyperlinks); 
     } 
     catch 
     { 
      sourceItem.Editing.CancelEdit(); 
     } 
     finally 
     { 
      sourceItem.Editing.EndEdit(); 
     } 
    } 
} 

之后,原始项目可以被删除。

item.Recycle(); 

一些Sitecore的场类型(如图片字段)具有path属性,它应该被更新,但它不应该是难以奏效的是到上面的代码。

相关问题