gpt4 book ai didi

c# - 第一次在 SItecore 中保存后如何停止自定义 OnSaving 事件?

转载 作者:行者123 更新时间:2023-11-30 23:28:23 34 4
gpt4 key购买 nike

在将自定义 OnSaving 事件应用到保存链中的第一项后,我试图停止它。

但到目前为止我还不能,最后我遇到了一个 stackoverflow 异常。

有没有一种简单的方法可以做到这一点?

最好的问候,

罗宾

private void AddOrRemoveRedirectingItemIdFromSavingItemIdList(Item savingItem, SitecoreEventArgs sitecoreEventArgs)
{
ItemLink[] referers = Globals.LinkDatabase.GetReferrers(savingItem);

var guidList = new List<ID>();

foreach (ItemLink link in referers)
{
// checking the database name of the linked Item
if (!link.SourceDatabaseName.Equals(Context.ContentDatabase.Name, StringComparison.CurrentCultureIgnoreCase))
{
continue;
}

Item item = Context.ContentDatabase.Items[link.SourceItemID, savingItem.Language];

// adding the Item to an array if the Item is not null
if (item == null || item.Fields["301Redirect"] == null || item.Fields["301RedirectedTo"] == null)
{
continue;
}

// Update the saving item ids
CheckboxField redirectField = item.Fields["301Redirect"];

if (redirectField.Checked)
{
guidList.Add(item.ID);
}
}

if (guidList.Any())
{
this.SaveIDsToEditingItem(savingItem, guidList, false);
}
}

private void SaveIDsToEditingItem(Item editingItem, IEnumerable<ID> guidList, bool forceModified)
{
Field redirectedToFromItemId = editingItem.Fields["301RedirectedToFromItemId"];

using (new EditContext(editingItem))
{
// Saving the redirected items ids
string redirectedToFromItemIdOld = redirectedToFromItemId.Value;
string redirectedToFromItemIdNew = string.Join("\n", guidList.Select(guid => guid.ToString()));

// if the values are not changed
if (redirectedToFromItemIdNew.Equals(redirectedToFromItemIdOld))
{
return;
}

redirectedToFromItemId.Value = redirectedToFromItemIdNew;
if (forceModified)
{
editingItem.RuntimeSettings.ForceModified = true;
}

}
}
}

最佳答案

您可以通过两种方式执行此操作。更好的方法是从 SaveIDsToEditingItem 中删除 using (new EditingContext(editingItem) 部分。在 OnItemSaving 事件中,对savingItem 将被保留。

或者,如果您需要出于某种原因使用编辑上下文,您需要在SaveIDsToEditingItem 方法中使用EventDisabler:

private void SaveIDsToEditingItem(Item editingItem, IEnumerable<ID> guidList, bool forceModified)
{
Field redirectedToFromItemId = editingItem.Fields["301RedirectedToFromItemId"];

using (new EventDisabler())
{
using (new EditContext(editingItem))
{
// Saving the redirected items ids
string redirectedToFromItemIdOld = redirectedToFromItemId.Value;
string redirectedToFromItemIdNew = string.Join("\n", guidList.Select(guid => guid.ToString()));

// if the values are not changed
if (redirectedToFromItemIdNew.Equals(redirectedToFromItemIdOld))
{
return;
}

redirectedToFromItemId.Value = redirectedToFromItemIdNew;
if (forceModified)
{
editingItem.RuntimeSettings.ForceModified = true;
}
}
}
}

这将防止再次触发 OnSaving 事件。

关于c# - 第一次在 SItecore 中保存后如何停止自定义 OnSaving 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007791/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com