1

I am trying to create an SPFx web part using SharePoint 2016. When adding PnP to SharePoint 2016, it's giving me errors and not working like when I add it to a SharePoint online SPFx web part. How can I update a list item field to add the current user to it (or remove the current user from that field)?

I cannot find the API to do this requirement.

1 Answer 1

0

How to update a person field using spHttpClient

A few things to note:

  1. Before doing the actual update you must ensure the user Id of the user, this is what you will input as the field value.
  2. You must add Id to your field name. If the field name is Personyou should use PersonIdin the update body.
private updatePeopleField(username: string, listname: string, itemid: string) {
    let client = this.props.context.spHttpClient;
    let clientconfig = SPHttpClient.configurations.v1;
    let options:ISPHttpClientOptions = {
      body: JSON.stringify({'logonName' : username})
    };
    client.post("/_api/web/ensureuser", clientconfig, options).then((res:SPHttpClientResponse) => {
      res.json().then(json => {
        return json.Id;
      }).then(userid => {
        let body= JSON.stringify({
          '__metadata': { 'type': `SP.Data.${listname}ListItem` },
        'PersonId': userid});

        let updateoptions = {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'Content-type': 'application/json;odata=verbose',
            'odata-version': '',
            'IF-MATCH': '*',
            'X-HTTP-Method': 'MERGE'
            },
          body: body
        };
        client.post(`/_api/web/lists/getByTitle('${listname}')/items('${itemid}')`, clientconfig , updateoptions)
          .then((response: SPHttpClientResponse) => {
            console.log('Item updated!');
          });
      });
    });
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.