[英]How to programmatically restore children Sitecore items?
I can currently delete items by calling item.DeleteChildren()
and if there is an error I would like to restore those items by having the original item list var originalItems = item.GetChildren();
我目前可以通过调用
item.DeleteChildren()
删除项目,如果出现错误,我想通过使用原始项目列表来恢复这些项目var originalItems = item.GetChildren();
but how can I restore them so that the values that were inside those template fields also remain? 但是如何还原它们,以便保留那些模板字段中的值?
I tried executing the following but all that does is recreate the template without the field values. 我尝试执行以下操作,但所有操作都是重新创建没有字段值的模板。
foreach (Item backupItem in backupItems)
{
item.Add(backupItem.Name, backupItem.Template);
}
You can archive them instead of deleting them and the restore them if need be. 您可以存档它们,而不是删除它们并根据需要还原它们。
http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2013/08/archiving-recycling-restoring-and-deleting-items-and-versions-in-the-sitecore-aspnet-cms.aspx http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2013/08/archiving-recycling-restoring-and-deleting-items-and-versions-in- the-sitecore-aspnet-cms.aspx
Code via John West 通过John West进行编码
Sitecore.Data.Items.Item item = Sitecore.Context.Item;
Sitecore.Diagnostics.Assert.IsNotNull(item, "item");
Sitecore.Data.Archiving.Archive archive =
Sitecore.Data.Archiving.ArchiveManager.GetArchive("archive", item.Database);
foreach (Sitecore.Data.Items.Item child in item.Children)
{
if (archive != null)
{
// archive the item
archive.ArchiveItem(child);
// to archive an individual version instead: archive.ArchiveVersion(child);
}
else
{
// recycle the item
// no need to check settings and existence of archive
item.Recycle();
// to bypass the recycle bin: item.Delete();
// to recycle an individual version: item.RecycleVersion();
// to bypass the recycle bin for a version: item.Versions.RemoveVersion();
}
}
To restore, use the same Archive class. 要还原,请使用相同的Archive类。
using (new SecurityDisabler())
{
DateTime archiveDate = new DateTime(2015, 9, 8);
string pathPrefix = "/sitecore/media library";
// get the recyclebin for the master database
Sitecore.Data.Archiving.Archive archive = Sitecore.Data.Database.GetDatabase("master").Archives["recyclebin"];
// get as many deleted items as possible
// where the archived date is after a given date
// and the item path starts with a given path
var itemsRemovedAfterSomeDate =
archive.GetEntries(0, int.MaxValue)
.Where(entry =>
entry.ArchiveDate > archiveDate &&
entry.OriginalLocation.StartsWith(pathPrefix)
).ToList();
foreach (var itemRemoved in itemsRemovedAfterSomeDate)
{
// restore the item
archive.RestoreItem(itemRemoved.ArchivalId);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.