Search This Blog

Saturday, July 8, 2017

Add Users In Email or Name in SharePoint Group


<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
                <SharePoint:ListItemProperty Property="BaseName" maxlength="40" runat="server"/>
<ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
                <meta name="GENERATOR" content="Microsoft SharePoint" />
                <meta name="ProgId" content="SharePoint.WebPartPage.Document" />
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <meta name="CollaborationServer" content="SharePoint Team Web Site" />
                <SharePoint:ScriptBlock runat="server">
                var navBarHelpOverrideKey = "WSSEndUser";
                </SharePoint:ScriptBlock>
<SharePoint:StyleBlock runat="server">
body #s4-leftpanel {
                display:none;
}
.s4-ca {
                margin-left:0px;
}
</SharePoint:StyleBlock>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderSearchArea" runat="server">
                <SharePoint:DelegateControl runat="server"
                                ControlId="SmallSearchInputBox"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
                <SharePoint:ProjectProperty Property="Description" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<SharePoint:ScriptLink name="clienttemplates.js" runat="server" LoadAfterUI="true" Localizable="false"/>
<SharePoint:ScriptLink name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false"/>
<SharePoint:ScriptLink name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false"/>
<SharePoint:ScriptLink name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false"/>
<SharePoint:ScriptLink name="sp.js" runat="server" LoadAfterUI="true" Localizable="false"/>
<SharePoint:ScriptLink name="sp.runtime.js" runat="server" LoadAfterUI="true" Localizable="false"/>
<SharePoint:ScriptLink name="sp.core.js" runat="server" LoadAfterUI="true" Localizable="false"/>

<script src="../SiteAssets/Script/jquery-3.1.1.min.js"></script>
<style type="text/css">
    
.ms-cui-topBar2
{
                display:none;
}
    </style>
    <script type="text/javascript">
    // Run your custom code when the DOM is ready.
$(document).ready(function () {


      retrieveListItems();
      initializePeoplePicker('peoplePickerDiv');
     
    
   
});


// Render and initialize the client-side People Picker.
function initializePeoplePicker(peoplePickerElementId) {

    // Create a schema to store picker properties, and set the properties.
    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = true;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '280px';

    // Render and initialize the picker.
    // Pass the ID of the DOM element that contains the picker, an array of initial
    // PickerEntity objects to set the picker value, and a schema that defines
    // picker properties.
    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
    //getUserInfo();
}

var userdomainname='';
// Query the picker for user information.
function getUserInfo() {

    // Get the people picker object from the page.
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    var userInfo = '';
    for (var i = 0; i < users.length; i++) {
        var user = users[i];
            for (var userProperty in user) {
            userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
        }
    }
    // Get user keys.
    if(users.length !=0)
    {
                      var keys = peoplePicker.GetAllUserKeys();
                      userdomainname=keys;
                      var myDdl = document.getElementById("ddlCategory");
                      if (myDdl.selectedIndex!=0)
                      {
                       addUserToSharePointGroup();
                      }
                       if((myDdl.selectedIndex==-1) ||(myDdl.selectedIndex==0))
                      {
                         alert('Please select list name!');
                      }
      }else
      {
                alert('Please enter user name!');
      }
  

}
function addUserToSharePointGroup()
{
      var strgroupName='';
      var mulValDropdowns = document.getElementById('ddlCategory'),storeDropVal, i;
      for(i = 0; i < mulValDropdowns.length; i++)
      {
        storeDropVal= mulValDropdowns[i];
         if (storeDropVal.selected)
        {
        strgroupName=storeDropVal.value;
       // alert(strgroupName);
        var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        var clientContext = new SP.ClientContext(siteUrl);
        var collGroup = clientContext.get_web().get_siteGroups();
        var oGroup = collGroup.getByName(strgroupName);
         //ensure SP User
        var userdomainVal=userdomainname;
        // alert(userdomainVal);
        var auserval=userdomainVal.split("|")[1];
         // alert(auserval);
        var usr2 = clientContext.get_web().ensureUser(auserval);
       //Get all SP Users in SP Group
        var userCollection = oGroup.get_users();
        //Add User to Group
        var oUSR2 = userCollection.addUser(usr2);
        clientContext.load(oUSR2);
        clientContext.load(userCollection); 
      clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
     }
  }
}
function onQuerySucceeded() {  
   
     window.frameElement.commitPopup();
     alert('User has been  added in email notification!');

}
function onQueryFailed(sender, args) {
                //flag=1;
                //if(flag=1)
                //{
                                alert('Please enter user name!');
                //}
  
}
//Bind Values to the DropDown
var ItemContainer = { ItemList: [] };
  function retrieveListItems() {
         var clientContext = new SP.ClientContext.get_current();
         var oList = clientContext.get_web().get_lists().getByTitle('UpdateUsersInEmailNotificationGroup');
         var camlQuery = new SP.CamlQuery();
         //camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>'); 
         camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' Ascending='True'/></OrderBy></Query></View>");       
         this.collListItem = oList.getItems(camlQuery);
         clientContext.load(collListItem);
         clientContext.executeQueryAsync(
             Function.createDelegate(this, this.onListDataLoadQuerySucceeded),
             Function.createDelegate(this, this.onListDataLoadQueryFailed));
     }
    
     
      function onListDataLoadQuerySucceeded(sender, args) {
       
         var listItemInfo = '';
         var listItemEnumerator = collListItem.getEnumerator();
         while (listItemEnumerator.moveNext()) {
             var oListItem = listItemEnumerator.get_current();
             var tempItem = { Text:oListItem.get_item('Title'), Value: oListItem.get_item('GroupNameEmailNotification') };
             ItemContainer.ItemList.push(tempItem);
         }
        fillDropDown();
     }
   
     function onListDataLoadQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     }


        function fillDropDown() {
         var ddlCategory = document.getElementById('ddlCategory');
         if (ddlCategory != null) {
             for (var i = 0; i < ItemContainer.ItemList.length; i++) {
                 var theOption = new Option;
                 theOption.text = ItemContainer.ItemList[i].Text;
                 theOption.value = ItemContainer.ItemList[i].Value;
                 ddlCategory.options[i] = theOption;
               
               }
           
             var totalLenCount= ItemContainer.ItemList.length;
            // alert(a);
             var myDdl = document.getElementById("ddlCategory");
             var myOption = document.createElement("OPTION");
             myOption.innerText = "--Select--";
             myDdl.options.insertBefore(myOption, myDdl.options[myDdl.options.length -totalLenCount]);       

         }
     }
    
    
    </script>
   
    
      <table id="tblAddUserLogin">
      <tr><td><div id="divAddUser"><b>Add User :</b><div id="peoplePickerDiv" style="margin-left:123px;margin-top:-20px;"></div></div></td></tr>
      <tr><td style="color:red;padding-left:121px;margin-top:17px;position:absolute;font-style:italic;font-size:8pt;">*Multiple Selection Allowed (Ctrl+Select)</td></tr>
      <tr><td><div id="divSelectItems" style="padding-top:30px;"><b>Alert type:</b><select id="ddlCategory" style="margin-left:60px;height:220px" multiple="multiple"><option value="01">Select</option></select></div></td></tr>
      <tr><td><div id="divbtnUserInfoSubmit" style="float:right;"><input type="button" value="Submit" onclick="getUserInfo();" style="background:lightgray;color:black;font-weight:bold"/></div></td></tr></table>
      </asp:Content>



No comments:

Post a Comment