Updating a Managed Metadata field in SharePoint Framework (SPFx) with the latest version of PnP.js (SPFI) is straightforward once you understand the basics. Managed Metadata fields are used to tag items with terms from a SharePoint Term Store.
In this article, we’ll explain how to use the validateUpdateListItem method from PnP.js to update a Managed Metadata field. The process is simplified, with easy-to-follow steps.
What is validateUpdateListItem?
The validateUpdateListItem method allows you to update list items in SharePoint by sending the field values in a format that SharePoint expects. This is especially useful for complex field types like Managed Metadata, People fields, or Lookup fields.
Here are the steps
1. SPFI Initialization: The spfi instance is configured using the SPFx method to integrate with the SharePoint Framework context.
2. Metadata Value Format: Managed Metadata field values are formatted as Label|GUID.
- Label: The name of the term (e.g., "Technology").
- GUID: The unique identifier of the term in the Term Store.
3. Updating the Field: The validateUpdateListItem method accepts an array of updates, where each update specifies the FieldName and FieldValue.
4. Error Handling: Errors are caught in the catch block, making it easier to debug issues.
import { spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/lists";
import "@pnp/sp/webs";
async function updateManagedMetadataField(
listName: string,
itemId: number,
fieldName: string,
termLabel: string,
termGuid: string
): Promise<void> {
try {
// Configure PnP.js SPFI
const sp = spfi().using(SPFx(this.context));
// Prepare the field value for a Managed Metadata field
const metadataValue = `${termLabel}|${termGuid}`;
// Use validateUpdateListItem to update the item
await sp.web.lists.getByTitle(listName).items.getById(itemId).validateUpdateListItem([
{
FieldName: fieldName,
FieldValue: metadataValue,
},
]);
console.log("Managed Metadata field updated successfully.");
} catch (error) {
console.error("Error updating Managed Metadata field:", error);
}
}
Here’s how you would call the updateManagedMetadataField function
await updateManagedMetadataField(
"Documents", // List name
1, // Item ID
"Category", // Managed Metadata field internal name
"Technology", // Term label
"abc12345-6789-def0-1234-56789abcdef0" // Term GUID
);
Conclusion
Using the validateUpdateListItem method in the latest version of PnP.js makes updating Managed Metadata fields in SPFx much easier and cleaner. The key is formatting the field value correctly and ensuring your PnP.js configuration is set up properly.
This approach reduces the complexity of handling Managed Metadata fields and streamlines your SharePoint Framework development workflow.