Thursday, January 22, 2015

Create Appointment via REST

Here is a short piece of Javascript code on how to create an appointment in CRM 2013 through REST.
I'm using CRMRestKit library to simplify the code.

function CreateNextAppointmentRequest(nextdate, accountid, listRequired) {
var retval;
appointment = new Object();
appointment.ScheduledStart = RealDolmen.DateToCRMFormat(nextdate);
if (accountid.id != null) {
appointment.RegardingObjectId = { Id: accountid.id, LogicalName: accountid.typename };
}
CrmRestKit.Create('Appointment', appointment, false).then(function (data) {
retval = data.d.ActivityId;
// The ActivityParties can't be stored directly into the Appointment activity,
// therefor we need to create and link them to the activity afterwards
for (var i = 0; i < listRequired.length; i++) {
var attendee = new Object();
attendee.PartyId = { Id: listRequired[i].id, LogicalName: listRequired[i].typename };
attendee.ParticipationTypeMask = { Value: 5 }; // https://msdn.microsoft.com/en-us/library/gg328549.aspx
attendee.ActivityId = { Id: retval, LogicalName: "appointment" };
CrmRestKit.Create('ActivityParty', attendee, false).then(function (data) { }, RealDolmen.onRestError);
}
// The ActivityParties can't be stored directly into the Appointment activity,
// therefor we need to create and link them to the activity afterwards
var organizer = new Object();
organizer.PartyId = { Id: Xrm.Page.context.getUserId(), LogicalName: "systemuser" };
organizer.ParticipationTypeMask = { Value: 7 }; // https://msdn.microsoft.com/en-us/library/gg328549.aspx
organizer.ActivityId = { Id: retval, LogicalName: "appointment" };
CrmRestKit.Create('ActivityParty', organizer, false).then(function (data) { }, RealDolmen.onRestError);
}, RealDolmen.onRestError);
return retval;
}
function onRestError(xhr, status, errorThrown) {
var msg = JSON.parse(xhr.responseText).error.message.value;
alert('Rest error: ' + msg);
},