M365 Dev Blog

Convert PnP TaxonomyPicker selection to update value

TaxonomyPicker update

I am a big fan of the PnP reusable controls and previously delivered some sessions about them. You can find the slides for one session on this blog post. One of my favorite controls is the TaxonomyPicker control, which I often use in custom forms to update list columns.

When using the PnP TaxonomyPicker reusable control to let the user select values for a managed metadata list field in SharePoint, you have to convert that selection into an object that you can then pass to the REST api when updating the field value.

The following function does exactly that. It receives the TaxonomyPicker selection as an array of objects and returns a string concatenation to update the field value.

Update April 2020 – I have fixed a bug updating multi-value fields when only one option was selected

const getManagedMetadataFieldValue = (terms: IPickerTerm[]): string => {
  let termValue = "";
  if (terms.length > 1) {
    for (const term of terms) {
      termValue += `${term.name}|${term.key};`;
    }
  } else {
    termValue += `${terms[0].name}|${terms[0].key}`;
  }
  return termValue;
};

I generally have this function on a utilities collection which I use on most projects. I can just use it whenever I need and forget about the specific format required for the metadata fields.

You can use this function together with PnPjs to easily update the value in SharePoint by updating the hidden note field that is generated for each managed metadata field.

await list.items.getById(itemId).update({
    // update hidden note fields associated with the managed metadata fields
    'NoteFieldName': selectedTerms ? getManagedMetadataFieldValue(selectedTerms) : null
});

Enjoy!

Exit mobile version