Sharepoint Rest Api in SPFX Update/Create taxonomy field value

 Scenario - creating custom form for SPListItem, with stuff... all html/css/js/ts

When sending primitive values such as string/number/bool/choice, you just need to find the internal name of your field and give the actual value, example:

Title : "My Awesome Achievements!!"

to find the internal name just go to your SPList => list settings -> click your column => on the end of the URL you will find &Field=MyFieldInternalName

so if my field is named "My Best Quality" and you click that you should see something like "myBestQuality" and your code should send

  Title : "My Awesome Achievements!!",

  myBestQuality : "I Can Think!" 

}

PS - the internal name can be very very different from the Display Name.

PS2 -  the internal name be encoding like "_x8473_x8573", in that case your internal name is "odata__x8473_x8573"


When we want People columns we need to get the userId and send that while adding "Id" to the internal name like:

  Title : "My Awesome Achievements!!",

  myBestQuality : "I Can Think!", 

  projectManagerId: 148, 

}

I wont get into how we get our list of users, but... use this endpoint "/_api/web/SiteUsers"


For TAXONOMY fields it gets interesting...

PS3 - get your taxo tree with this awesome code from git


Single Taxo need just the term guid

valueForRest = {

    TermGuid: valueOfGuid, 

    WssId: -1

}

and then the body is

  Title : "My Awesome Achievements!!",

  myBestQuality : "I Can Think!", 

  projectManagerId: 148, 

  singleTaxoFieldvalueForRest

}


and now for the real fun... TaxonomyFieldTypeMulti


first, you need the Hidden Name of the column which is a guid of sort, and can be acquired via the api like this 

say i have a field named "My Coool Multi Taxo" (thats the display name!) i will go to this endpoint:

/sites/New-Proj/_api/web/lists/GetByTitle('My Coll List')/Fields/GetByTitle('My Coool Multi Taxo_0')/InternalName

that will retrieve something like "h01c0d38859b5538868471f40a78f4c4" and that is our column name for the body.

next, is how we build the value for this multi taxo, its like "'-1;#TermName|TermGuid;'" and seperated by #.



=======================================================

=======================================================

=======================================================



Let me show my final code, the HTML is rendered with angular, your can easily remake it in your TS, print the options with a for loop, and use "addEventListener" for "input" event.

      <select multiple (input)="emitInput($event)">

        <option value="" selected></option>

        <option *ngFor="let c of plTaxo" [value]="c.guid" >{{c.name}}</option>

     </select>  

next creating the REAL value (the "h01c0d38859b5538868471f40a78f4c4" i took manually since i needed only 1). event is the JS event from the "select" element "input" event

  emitInput(event: any) {

        let terms = event.target.selectedOptions as HTMLCollection

        value = ''

        for (let i = 0; i < terms.length; i++) {

          let t = terms[i] as HTMLOptionElement

          value += `-1#;${t.text}|${t.value};#`

        }

        value = value.slice(0, -1)

        this.myService.setValueToBody(

             "h01c0d38859b5538868471f40a78f4c4"value )

}


BONUS my generic create item function:

    public createListItemInWeb(web:string, listName: string, body: object): Promise<any> {
        const spOpts: string = JSON.stringify(body);
        let promise = new Promise((resolve, reject) => {
            this.context.spHttpClient.post(`${web}/_api/web/lists/GetByTitle('${listName}')/items`, SPHttpClient.configurations.v1, {
                headers: {
                    'Accept': 'application/json;odata=nometadata',
                    'Content-type': 'application/json;odata=nometadata',
                    'odata-version': ''
                },
                body: spOpts
            })
                .then((response: SPHttpClientResponse) => {
                     response.json().then((responseJSON: JSON) => {
                        console.log(responseJSON);
                        resolve(responseJSON);
                    });
                });
        });
        return promise
    }


HAVE FUN

Comments

  1. Great post! Very informative and clearly explained. Thanks for sharing such valuable content. If anyone is looking to upskill in Microsoft Power Apps, we offer comprehensive Power Apps Training in Hyderabad with hands-on experience. Feel free to check it out!

    ReplyDelete

Post a Comment

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

SPFx with Angular, Full tutorial

Asp.Net Ending Response options, Response.End() vs CompleteRequest()