5


I wrote some code to get the current user groups by CSOM.

function getCurrentUser() {
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    clientContext.load(allGroups);
    this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededUser), Function.createDelegate(this, this.onQueryFailedUser));
}
function onQuerySucceededUser() {
    //debugger;
    var groups = currentUser.get_groups();
    var groupsEnum = groups.getEnumerator();
    while (groupsEnum.moveNext()) {
        //handle group
    }
}

But I get this error:

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

on this line: groups.getEnumerator();
How can I solve it?

6

Move this line

var groups = currentUser.get_groups();

To your getCurrentUser method and make sure to load it

this.clientContext.load(groups);

before executing the request, this way you will have it loaded in your success-function

3

The code should look like this:

function getCurrentUser() {
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.allGroups = currentUser.get_groups();    
    clientContext.load(allGroups);
    this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededUser), Function.createDelegate(this, this.onQueryFailedUser));
}
function onQuerySucceededUser() {
    var groupsEnum = allGroups.getEnumerator();
    while (groupsEnum.moveNext()) {
        //handle group
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.