1

I want to add a user to SharePoint group (in another site collection) using JavaScript API.

Here's my code

 var clientContext = new SP.ClientContext("https://MYURL/sites/dev2/");
            var groupCollection = clientContext.get_web().get_siteGroups();
            // Get the visitors group, assuming its ID is 4.
            visitorsGroup = groupCollection.getByName("Editorial Workflow Approvers");
            user = clientContext.get_web().get_currentUser();
            var userCollection = visitorsGroup.get_users();
            //userCollection.add(user);

            //clientContext.load(user);

        //test
            var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

        // Get information about all users.
            var users = peoplePicker.GetAllUserInfo();
            var userInfo = '';
            var MyFoundUser;
            for (var i = 0; i < users.length; i++) {
                var user = users[i];

                //Test
                var UserLoginName = user["Key"].split('|')[2];

                MyFoundUser = clientContext.get_web().ensureUser(user["Key"]);
                clientContext.load(MyFoundUser);
                //Test
                break;
            }
        //test

            userCollection.add(MyFoundUser);

            clientContext.load(visitorsGroup);
            clientContext.executeQueryAsync(Function.createDelegate(this, function onQuerySucceeded() {
                alert(user.get_title() + " added to group " + visitorsGroup.get_title());
            }), Function.createDelegate(this, function onQueryFailed(sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }));

I get following error: "Request failed. The parameter loginname cannot be empty or bigger than 251 characters".

When i add current user which i get in 'user' variable it works fine.

just to add i have used both "userLoginName" variable and "user["Key"]" (in current code). both fail

Please suggest what i am doing wrong. Or if there's any other way to achieve this please let me know.

1 Answer 1

1

Try adding the MyFoundUser to the context: clientContext.load(MyFoundUser). I am looking at my code which does similar, but I add the user in one request, and then add the user to a group in another request. You might have to make 2 calls, but I think loading the user into the context should work.

HTH

1
  • hi david. I had already added MyFoundUser in clientcontext (Please see the code). anyways, I achieved my functionality by calling sharepoint soap service (using SPServices). Thanks for your comment..
    – mry
    Sep 24, 2013 at 9:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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