Event Registration Sharepoint 2013
SP doesn't provide any OOB way to stop registration if seats are filled. Or any way to unregister from an event.
To do this I created 2 code blocks, one for registration and another for unregistering.
The basic idea was from this blog when I was searching for any code to do this. However this uses the Infopath. Since Infopath is becoming obsolete, I had to create ajax and java script updates to lists.
Register and Unregister from an event
Steps to Follow
1. Create
Create 2 lists "Events" & "Volunteer Signup"
I will provide steps to perform for the code to execute.
Register
<script language="javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getCurrentUser);
document.getElementById("MeetingID_4bc56f64-2522-4a19-aa15-49d3052656ac_$TextField").readOnly = true;
document.getElementById("Username_39f28be1-f278-4d89-a82f-330e9d28a30d_$TextField").readOnly = true;
});
var Validation;
function PreSaveAction() {
var validation2 = currentUser + Id;
if(validation2 == Validation ){
var form = document.getElementsByClassName('ms-formtable')[0];//new form
GetAncestor(form,'DIV').innerHTML = '<h1>
You have already registered for this event. </h1>
';
return false;
}
var usernamefield = document.getElementById("Username_39f28be1-f278-4d89-a82f-330e9d28a30d_$TextField");
usernamefield.value = currentUser;
var flag = document.getElementById("Flag_83779f1c-da98-4b41-becd-5e7132d96383_$TextField")
//flag.value = "1";
return true;
}
//Get Current User
var currentUser;
function getCurrentUser() {
try {
var clientContext = new SP.ClientContext.get_current();
var tempcurrentUser = clientContext.get_web().get_currentUser();
clientContext.load(tempcurrentUser);
clientContext.executeQueryAsync(function () {
var index = tempcurrentUser.get_loginName().indexOf('|') + 1;
currentUser = tempcurrentUser.get_loginName().split("\\")[1]
return currentUser;
}, queryFailure);
}
catch (err) {
queryFailure();
}
}
function queryFailure () {
alert('error');
}
function getUrlParameter( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
function populateNewForm()
{
document.getElementById("MeetingID_4bc56f64-2522-4a19-aa15-49d3052656ac_$TextField").value = getUrlParameter("meeting_id");
}
_spBodyOnLoadFunctionNames.push("populateNewForm")
_spBodyOnLoadFunctionNames.push("myfunction")
var Id;
var validation2;
function myfunction(){
var siteurl = _spPageContextInfo.webAbsoluteUrl;
Id = results[1];
$.ajax({
url: siteurl + "/_api/web/lists/getbytitle('volunteer signup')/items?$filter=MeetingID%20eq%20" + Id,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
Validation = data.d.results[i].ValidationColumn;
}
},
error: function (data) {
alert("Error: "+ data);
}
});
}
</script>
Unregister
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button id="unregister" type="button">Unregister</button>
<script type="text/javascript">
var MyProject = {};
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getCurrentUser);
MyProject.fldValue = $('h3:contains("StaticID")').closest('td').next('td').text();
MyProject.remseats = $('h3:contains("RemainingSeats")').closest('td').next('td').text();
MyProject.fildseats = $('h3:contains("FilledSeats")').closest('td').next('td').text();
$('h3:contains("SeatsIncrement")').closest('tr').hide();
$('h3:contains("RemainingSeats")').closest('tr').hide();
});
$('#unregister').on('click', function (e) {
myfunction();
});
var Flag;
var User;
function myfunction(callbackFunction){
var siteurl = _spPageContextInfo.webAbsoluteUrl;
var Id = $('td.ms-formlabel:contains("StaticID")').siblings(".ms-formbody").text();
$.ajax({
url: siteurl + "/_api/web/lists/getbytitle('volunteer signup')/items?$filter=((MeetingID%20eq%20'" + Id + "') and (Username eq '" + currentUser + "'))",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
if(data.d.results.length > 0){
for (var i = 0; i < data.d.results.length; i++) {
Flag = data.d.results[i].Flag;
User = data.d.results[i].Username;
if(User==currentUser){
checkifregistered();
break;
}//else
// {
// document.getElementsByClassName('ms-rtestate-field')[0].innerHTML = '<h1>You did not register for this Event. To register please click on the Register link below</h1>
';
// return;
// }
}
}
else
{
document.getElementsByClassName('ms-rtestate-field')[0].innerHTML = '<h1>
You did not register for this Event. To register please click on the Register link below</h1>
';
return;
}
},
error: function (data) {
alert("Error: "+ data);
}
});
}
//Get Current User
var currentUser;
function getCurrentUser() {
try {
var clientContext = new SP.ClientContext.get_current();
var tempcurrentUser = clientContext.get_web().get_currentUser();
clientContext.load(tempcurrentUser);
clientContext.executeQueryAsync(function () {
var index = tempcurrentUser.get_loginName().indexOf('|') + 1;
currentUser = tempcurrentUser.get_loginName().split("\\")[1]
return currentUser;
}, queryFailure);
}
catch (err) {
queryFailure();
}
}
function queryFailure () {
alert('error');
};
function checkifregistered(){
if(Flag == 1 && (User==currentUser)){
Update();
//UpdateCount();
document.getElementsByClassName('ms-rtestate-field')[0].innerHTML='You are now unregistered from the event';
//decrement the seats filled and increment seats available
}else{
document.getElementsByClassName('ms-rtestate-field')[0].innerHTML = '<h1>
You did not register for this Event. To register please click on the Register link below</h1>
';
//alert("You didn't register for this Event");
if(User != currentUser) return;
}
}
//Update List item to change list item field Flag to flag 1 for register
//var sField1 = $('h3:contains("StaticID")').closest('td').next('td').text();
// occurs when a user clicks the update button
function Update() {
var listName = "volunteer signup";
var url = _spPageContextInfo.siteAbsoluteUrl;
var MeetingID = MyProject.fldValue;
var title = "0";
updateListItem(MeetingID, listName, url, title, function () {
//alert("Item updated, refreshing avilable items");
//Read();
//Run Update only if this ajax call succeedes.
UpdateCount();
}, function () {
alert("Error Unregistering,Please try again after few minutes");
});
}
// Delete Operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// itemId: the id of the item to update
// success: The function to execute if the call is succesull
// failure: The function to execute if the call fails
function updateListItem(MeetingID, listName, siteUrl, title, success, failure) {
//var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": "SP.Data.volunteer_x0020_signupListItem" },
"Flag": title
};
getListItemWithId(MeetingID, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"If-Match": data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}, function(data){
failure(data);
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
}
// READ SPECIFIC ITEM operation
// itemId: The id of the item to get
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function getListItemWithId(MeetingID, listName, siteurl, success, failure) {
var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=((MeetingID%20eq%20'" + MeetingID + "') and (Username eq '" + currentUser + "'))";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
if (data.d.results.length > 0) {
success(data.d.results[0]);
for (var i = 0; i < data.d.results.length; i++){
if(data.d.results[i].Username = User){ Console.log("matched the username") }
}
}
else {
failure("Multiple results obtained for the specified Id value");
}
},
error: function (data) {
failure(data);
}
});
}
//Update Count for remaining seats and Filleed seats
function UpdateCount(){
var siteUrl = '/apps/wbserves';
//function updateListItem() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Events');
this.oListItem = oList.getItemById(MyProject.fldValue);
var len = MyProject.remseats.trim();
var x = len++;
if(MyProject.fildseats == 1){
var y = 0;}else{
var y = MyProject.fildseats - 1;
}
//oListItem.set_item('RemainingSeats', len);
oListItem.set_item('FilledSeats', y);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
//alert('Item created: ' + oListItem.get_id());
}
function onQueryFailed(sender, args) {
//alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
//}
</script>
Comments
Post a Comment