How to stop an Item from being deleted with ItemDeleting RER?
-
23-01-2021 - |
Question
I created an Event Receiver that prevents an item if a checkbox is ticked however if I add the condition, the event receiver do not fire
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
{
using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
{
SPRemoteEventResult result = new SPRemoteEventResult();
if (properties.EventType == SPRemoteEventType.ItemDeleting)
{
List list = clientContext.Web.Lists.GetByTitle(properties.ItemEventProperties.ListTitle);
ListItem fieldItem = list.GetItemById(properties.ItemEventProperties.ListItemId);
if ((bool)fieldItem["CheckBox"])
{
result.Status = SPRemoteEventServiceStatus.CancelWithError;
result.ErrorMessage = "Error";
}
result.Status = SPRemoteEventServiceStatus.Continue;
}
return result;
}
}
La solution
Call Load and ExecuteQuery Before accessing item properties.
List list = clientContext.Web.Lists.GetByTitle(properties.ItemEventProperties.ListTitle);
ListItem fieldItem = list.GetItemById(properties.ItemEventProperties.ListItemId);
clientContext.Load(fieldItem);
clientContext.ExecuteQuery();
if((bool)fieldItem["CheckBox"]){
//....
}
Autres conseils
You can add properties.Cancel = true;
to cancel item from deleting.
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
{
using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
{
SPRemoteEventResult result = new SPRemoteEventResult();
if (properties.EventType == SPRemoteEventType.ItemDeleting)
{
List list = clientContext.Web.Lists.GetByTitle(properties.ItemEventProperties.ListTitle);
ListItem fieldItem = list.GetItemById(properties.ItemEventProperties.ListItemId);
if ((bool)fieldItem["CheckBox"])
{
result.Status = SPRemoteEventServiceStatus.CancelWithError;
result.ErrorMessage = "Error";
properties.Cancel = true;
}
result.Status = SPRemoteEventServiceStatus.Continue;
}
return result;
}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange