Requirement: To get all the user names from the SharePoint group "Deliverable Owners" and sync with a custom list called "Team Members" in a button click.
Solution: This is done using jQuery and SharePoint web services.
<script type=
"text/javascript"
src=
"https://siteurl/Documents/jquery-1.8.3.min.js"
></script>
<script type=
"text/javascript"
src=
"https://siteurl/Documents/jquery.SPServices-0.7.2.min.js"
></script>
<script type=
"text/javascript"
>
$(document).ready(function() {
$(
"#syncUsers"
).click(function()
//'syncUsers' is the ID of button control added in the CEWP
{
var errorOccured = DeleteUsersFromTeamMembersList();
if
(!errorOccured)
{
AddUsersToTeamMembersList();
}
});
});
// to delete the existing users from the custom list
function DeleteUsersFromTeamMembersList()
{
var errorOccured =
false
;
$().SPServices({
operation:
"GetListItems"
,
async:
false
,
debug:
true
,
listName:
"Team Members"
,
CAMLViewFields:
"<ViewFields></ViewFields>"
,
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode(
"z:row"
).each(function()
{
$().SPServices({
operation:
"UpdateListItems"
,
async:
false
,
debug:
true
,
batchCmd:
"Delete"
,
listName:
"Team Members"
,
ID: $(
this
).attr(
"ows_ID"
),
completefunc: function (xData, Status) {
msgData = xData.responseText;
isError = msgData.indexOf(
"ErrorText"
);
if
(isError > 0) {
// Error creating fields!
alert(
"Error deleted user names from Team Member list!"
);
errorOccured =
true
;
}
}
});
});
}
});
return
errorOccured;
}
//add all the users from the sharepoint group to custom list.
function AddUsersToTeamMembersList()
{
var alreadyProcessed =
false
;
var userName ;
var iD;
var userID;
var errorOccured =
false
;
$().SPServices({
operation:
"GetUserCollectionFromGroup"
,
groupName:
"Deliverable Owners"
,
completefunc: function (xData, Status) {
$(
"#results"
).text(xData.responseXML.xml);
$(xData.responseXML).find(
"User"
).each(function () {
userName = $(
this
).attr(
"LoginName"
);
iD = $(
this
).attr(
"ID"
);
userID = iD +
";#"
+userName;
$().SPServices({
operation:
"UpdateListItems"
,
<);
iD = $(
this
).attr(
"ID"
);
userID = iD +
";#"
+userName;
$().SPServices({
async:
false
,
batchCmd:
"New"
,
listName:
"Team Members"
,
valuepairs: [[
"User"
,userID ]],
completefunc: function(xData, Status)
{
msgData = xData.responseText;
isError = msgData.indexOf(
"ErrorText"
);
if
(isError > 0) {
// Error creating fields!
alert(
"Error synchronizing user names!"
);
errorOccured =
true
;
}
}
});
});
if
( errorOccured ==
false
)
{
alert(
"User name synchronized successfully."
);
$(window.location).attr(
'href'
,
'currentpagename.aspx'
);
}
}
});
}
</script>
Limitations & Prerequisite
- The performance of this code is affected based on the size of the user group.
- The Team Members custom list must have "User" field with people and group type.