Reference/Update the current item inside ItemAdded/ing and ItemUpdated/ing remote event receivers, is it available inside the SPRemoteEventProperties
-
08-02-2021 - |
Question
I am working on remote event receivers, and let say I want to update a field named ProjectID inside my ItemAdded, currently, I am executing a CAML query to get the current item >> update the ProjectID, as follow:-
public void ProcessOneWayEvent(SPRemoteEventProperties properties)
{
var listItemID = properties.ItemEventProperties.ListItemId;
var listTitle = properties.ItemEventProperties.ListTitle;
using (ClientContext context = Helpers.GetAppOnlyContext(properties.ItemEventProperties.WebUrl))
{
CamlQuery camlQuery = new CamlQuery();
context.Load(context.Web);
context.ExecuteQuery();
string webrelativeurl = context.Web.ServerRelativeUrl;
camlQuery.ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>{0}</Value></Eq></Where></Query></View>", listItemID);
ListItemCollection collListItem = context.Web.GetList(webrelativeurl + "/lists/" + "Projects").GetItems(camlQuery);
context.Load(collListItem, items => items.Include(
item => item.Id,
item => item["ProjectID"],
item => item["ID"],
item => item.RoleAssignments.Include(roleAssigned => roleAssigned.Member.Title, roleAssigned => roleAssigned.RoleDefinitionBindings)
));
context.ExecuteQuery();
//get the template id based on the entered Purpose
foreach (ListItem currentFilingSystemItem in collListItem)
{
ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();
ListItem listItem = context.Web.GetList(webrelativeurl + "/lists/" + "Projects").AddItem(listItemCreationInformation);
listItem["ProjectID"] = "ARQ-Project-" + listItem["ID"];
listItem.Update();
So is my approach correct? or I can directly reference the current item instead of getting it by CAML? the issue is that I can not reference properties.ListItem
as in the server-side event receivers.
Solution
In the SharePoint remote event receiver, it passes an SPRemoteEventProperties object, it doesn't have the current item as it is available in SSOM, but it has the origin listid and itemid, so using that we can fetch it from the list and use it. It is by design and you refer here
To update any field in the current item, you can use the below code, instead of CAML query, because we can fetch the list and list item using its ID's.
List requestList = clientContext.Web.Lists.GetById(properties.ItemEventProperties.ListId);
ListItem item = requestList.GetItemById(properties.ItemEventProperties.ListItemId);
clientContext.Load(item);
clientContext.ExecuteQuery();
item["Your column Name"] //this will have the current item value
item.Update();
clientContext.ExecuteQuery();