Search code examples
typescriptspfx

SPFx: Add a new item to existing List Folder (using pnp)


Does anyone know how to add a new item to a List Folder in Sharepoint Framework?

In this way I can add the item to the list MyList:

let list = pnp.sp.web.lists.getByTitle("MyList");    

list.items.add({
      Title: "itemName"
      }).then(r => { 

      console.log(r);
})

But I need it being created inside the folder MyList\MyFolder.

I have tried retrieving the folder in this way:

var folder= sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder");

but I cannot find a way to add items inside.


Solution

  • As Jackson wrote, it seems that it's not possibile to add an item to a List Folder with the sp-pnp-js library.

    So, doing some searches I have found that it is possible to use addValidateUpdateItemUsingPath for this purpose:

    const _spPageContextInfo=this.context.pageContext.legacyPageContext;
    const webUrl = _spPageContextInfo.webAbsoluteUrl;
    
    const listPath=webUrl+"/Lists/MyListInternalName";
    const folderName="MyFolderName";
    
    sp.site.rootWeb.lists.getByTitle("MyList").addValidateUpdateItemUsingPath([
        { FieldName: 'Column1', FieldValue: 'Value1'}, 
        { FieldName: 'Column2', FieldValue: 'Value2'}]    
      ,`${listPath}/${folderName}`).then(console.log);
    

    Then, it took me a little bit of extra time to understand how to set the FieldValue for User fields while using addValidateUpdateItemUsingPath (in this case using the user ID -as usual- to retrieve the user was not working).
    But I have found this way:

    {FieldName: 'ColumnUser', 
    FieldValue: JSON.stringify([{"Key": "i:0#.f|membership|"+"MyUserEmail"}])}