简体   繁体   中英

Add a user to a group programatically

Is it possible to add a user to a group via REST/sdk?

Scenario: We want to add all our users to a mandatory group on a regularly basis.

Thanks!
Max

you can get group ids from share point list like this

 function GetMandatoryGroups() {
        var context;
        var factory;
        var appContextSite;
        var oList;
        var collListItem;

        context = new SP.ClientContext(appweburl);
        factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostweburl);

        this.web = appContextSite.get_web();
        oList = this.web.get_lists().getByTitle('MandatoryGroups');
        context.load(oList);
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
        collListItem = oList.getItems(camlQuery);
        context.load(collListItem, 'Include(Title,Id)');

        context.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

 function successHandler() {
            MandatoryGroups = new Array();
            var listItemInfo = '';
            var listitemenumerator = collListItem.getEnumerator();

            while (listitemenumerator.moveNext()) {
                var olistitem = listitemenumerator.get_current();
                //listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
                MandatoryGroups.push(olistitem.get_item('Title'));
            }
            AutoJoinGroups();
            //  document.getElementById("message").innerHTML = 'Lists found' +   oList.get_title() + ':<ul>' + listItemInfo + '</ul>';
        }

        function errorHandler(sender, args) {
            document.getElementById("message").innerText =
                "Could not complete cross-domain call: " + args.get_message();
        }
    }

you can join users to the mendatory groups like this (after user logs in )

      function AutoJoinGroups() {

        yam.platform.request({
            // yam.request({
            url: "groups.json?mine=1",
            method: "GET",
            data: {},
            success: function (group) {

                //for ($i = 0; $i < MandatoryGroups.length; $i++) {
                //    if (!ArrayContains(MandatoryGroups[$i].toString(), group)) {
                //        joinGroupAsync(MandatoryGroups[$i].toString());
                //        setTimeout('', 10000);
                //       // setTimeout(joinGroupAsync(MandatoryGroups[$i].toString()),5000);
                //    } 
                //}
                var i = 0;
                function AsyncAutoJoinLoop() {
                    if (i < MandatoryGroups.length) {
                        if (!ArrayContains(MandatoryGroups[i].toString(), group)) {
                            setTimeout(function () {
                                joinGroupAsync(MandatoryGroups[i].toString());
                                i++;
                                if (i < MandatoryGroups.length) {
                                    AsyncAutoJoinLoop();
                                }
                            }, 3000)
                        }
                    }
                }
                AsyncAutoJoinLoop();
                // getMyGroups();
            },

            error: function (group) {
                console.error("There was an error with the request.");
            }
        });
    }

    function joinGroupAsync(id) {
        yam.platform.request({
            // yam.request({
            url: "group_memberships.json?group_id=" + id,
            method: "POST",
            data: {},
            success: function (group) {

            },

            error: function (group) {
                console.error("There was an error with the request.");
            }
        });
    }

you can add group to the sharepoint list like this.

  function InsertMandatoryItem() {
        var context;
        var factory;
        var appContextSite;
        var oListItem;

        context = new SP.ClientContext(appweburl);
        factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostweburl);

        this.web = appContextSite.get_web();
        var oList = this.web.get_lists().getByTitle('MandatoryGroups');

        var itemCreateInfo = new SP.ListItemCreationInformation();
        oListItem = oList.addItem(itemCreateInfo);
        oListItem.set_item('Title', InsertGroupId);
        oListItem.update();

        context.load(oListItem);
        context.executeQueryAsync(
            Function.createDelegate(this, onQuerySucceeded),
            Function.createDelegate(this, onQueryFailed)
        );
        function onQuerySucceeded() {
            //alert('Item created: ' + oListItem.get_id());
            // getMyGroups();
            // AutoJoinGroups();
            $.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);

        }

        function onQueryFailed(sender, args) {
            $.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
            alert('Request failed. ' + args.get_message() +
                '\n' + args.get_stackTrace());
        }
    }

You can remove remove group from sharepoint list like this

       function RemoveMandatoryGroup() {
        var context;
        var factory;
        var appContextSite;

        var collListItem;
        var itemId;
        context = new SP.ClientContext(appweburl);
        factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostweburl);

        this.web = appContextSite.get_web();
        var oList = this.web.get_lists().getByTitle('MandatoryGroups');
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + RemoveGroupId.toString() + "</Value></Eq></Where></Query></View>");

        collListItem = oList.getItems(camlQuery);
        context.load(collListItem, 'Include(Title,Id)');


        //  this.oListItem.deleteObject();

        context.executeQueryAsync(
            Function.createDelegate(this, onQuerySucceeded),
            Function.createDelegate(this, onQueryFailed)
        );
        function onQuerySucceeded() {
            var oListItem;
            var listitemenumerator = collListItem.getEnumerator();

            while (listitemenumerator.moveNext()) {
                var itemtoDelete = listitemenumerator.get_current();
                ////listItemInfo += '<li>ID:' + olistitem.get_id().toString() + ' GroupID: ' + olistitem.get_item('Title') + '</li>';
                //MandatoryGroups.push(olistitem.get_item('Title'));
                itemId = itemtoDelete.get_id();

            }
            oListItem = oList.getItemById(itemId);
            oListItem.deleteObject();
            context.executeQueryAsync(Function.createDelegate(this, onQueryDeleteSucceeded), Function.createDelegate(this, onQueryDeleteFailed));
            //alert('Item created: ' + oListItem.get_id());
            function onQueryDeleteSucceeded() {
                //alert('Request failed. ' + args.get_message() +
                //    '\n' + args.get_stackTrace());
                getMyGroups();
                $.getScript(scriptbase + 'SP.RequestExecutor.js', GetMandatoryGroups);
            }

            function onQueryDeleteFailed() {
                alert('Request failed. ' + args.get_message() +
                    '\n' + args.get_stackTrace());
            }
        }

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() +
                '\n' + args.get_stackTrace());
        }
    }

No, there isn't. This is by design. Yammer likes to entice with the carrot, not by the stick. What we've done is create communications to ask people to join a specific group.

The api does allow the ability for the currently logged to be joined to a specific group. Eg Put a link on a SharePoint site that says "Join the Yammer group", and have the action join that user to the group. You can see the details for how to do that here:

https://developer.yammer.com/restapi/#rest-groups

是的,在服装应用中,您可以在该用户登录时自动加入该用户。我在做同样的事情。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM