Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all lists root folder with SP.js

I need to get all root folders of lists on current web, with shrepoint client object model.

I try to use this code, but i have error

var context = SP.ClientContext.get_current();
var lists = context.get_web().get_lists();
context.load(lists);
context.executeQueryAsync(function (sender, args) {
    var enumerator = lists.getEnumerator();
    while (enumerator.moveNext()) {
       var list = enumerator.get_current();
       var rootFolder = list.get_rootFolder();
       context.load(rootFolder, 'ServerRelativeUrl');
       context.executeQueryAsync(
       function (sender, args) {
           //error
           var url = rootFolder.get_serverRelativeUrl();
           console.log(url);
       },
       function (sender, args) {
           console.log('error');
       });
    }
},
function (sender, args) {
     console.log('error');
});

Thanks

like image 229
user2944829 Avatar asked Mar 15 '26 21:03

user2944829


1 Answers

This error occurs because List.RootFolder property has not been initialized since it was not requested.

In order to load List.RootFolder replace the line:

context.load(lists);

with this one:

context.load(lists,'Include(RootFolder)');

But the specified example contains another flaws:

  • Since SP.ClientContext.executeQueryAsync method is async and it is used in a loop, it will not print all folders as you expect it to
  • There is no need to perform a subsequent query for ServerRelativeUrl property

Below is demonstrated the fixed version that prints root folders for all lists:

var context = SP.ClientContext.get_current();
var lists = context.get_web().get_lists();
context.load(lists,'Include(RootFolder)');
context.executeQueryAsync(function () {
    var enumerator = lists.getEnumerator();
    while (enumerator.moveNext()) {
       var list = enumerator.get_current();
       var rootFolder = list.get_rootFolder();

       var url = rootFolder.get_serverRelativeUrl();
       console.log(url);

    }
},
function (sender, args) {
     console.log('error');
});   
like image 184
Vadim Gremyachev Avatar answered Mar 17 '26 21:03

Vadim Gremyachev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!