December 12, 2019

SPFx: Changing Folder Content Type using PnPjs

Task

Needed to create Folders with custom Content Type in SharePoint document library from my SPFx web part, as there was a need to add some custom fields, such as Description, to the Folder item.

Solution

This one took a few hours to figure out, you need to do it in few steps as you cannot change the content type of a folder using sp.web.folders…update as REST API doesn’t allow ContentTypeId parameter when updating Folder content types, and you will get error:

“The property 'ContentTypeId' does not exist on type 'SP.Folder’. Make sure to only use property names that are defined by the type”

Also if you would use …folder.getItem(), it will fail if folder has special characters.

  1. Create folder as normal Folder
  2. Get list item ID of the folder
  3. Update folder as a list item
let etfn = await sp.web.getList(listUrl).getListItemEntityTypeFullName();

// first create folder
let far: FolderAddResult = await sp.web.folders.add(listUrl + '/' + targetParentFolderName + targetFolderName);

// then get list item ID of the folder
let fData: any = await sp.web.getFolderById(far.data.UniqueId).select('ID').listItemAllFields.get();            

// then get folder as list item
let item: Item = sp.web.getList(listUrl).items.getById(fData['ID']);

await item.update({
    ContentTypeId: 'CUSTOM_FOLDER_CONTENTTYPE',
    PF_FolderDescription: 'Some description...'
}, '*', etfn);

No comments:

Post a Comment