You are here:
Allow Agents to See Their Assigned Shifts with an Apex Trigger
Create an Apex trigger that lets an agent see their assigned shifts in their agent home tab. This trigger prevents the agent from seeing other agents’ assigned shifts.
Required Editions
Note Workforce Engagement is scheduled for retirement. See Workforce Engagement Retirement.
| View supported editions. |
Here's an example of how you can share assigned shifts with each agent.
Note Applying the trigger doesn’t remove sharing if the original service resource
is changed or removed. The code always tests for auto-sharing, even if that
isn’t needed.
// Trigger that occurs after a shift is inserted
trigger ShiftDemoTrigger on Shift (after insert) {
/* TODO Optimization, test if sharing object is available, replace boolean */
boolean needsToShareShift = true;
if (!needsToShareShift) {
return;
}
Map<Id, List<Id>> srIdsToShiftIds = new Map<Id, List<Id>>();
for(Shift newShift : Trigger.New) {
// map service resources to shifts to share with
if(newShift.ServiceResourceId != null) {
List<Id> shiftIdsForResource = srIdsToShiftIds.get(newShift.ServiceResourceId);
if(shiftIdsForResource == null){
shiftIdsForResource = new List<Id>();
}
shiftIdsForResource.add(newShift.Id);
srIdsToShiftIds.put(newShift.ServiceResourceId, shiftIdsForResource);
}
}
// Load the ServiceResources associated with the new shifts that were created.
List<ServiceResource> results = [SELECT RelatedRecordId, ResourceType FROM ServiceResource WHERE Id in :srIdsToShiftIds.keySet()];
if (!results.isEmpty()) {
List<ShiftShare> shareEntriesToCreate = new List<ShiftShare>();
for(ServiceResource serviceResource : results) {
// This is a shift for an Agent Service Resource so let's configure a share record for it
if (serviceResource.ResourceType == 'A') {
// shift ids that contain this service resource
List<Id> shiftIds = srIdsToShiftIds.get(serviceResource.Id);
if (shiftIds != null && !shiftIds.isEmpty()) {
for (Id shiftId : shiftIds) {
// New sharing record to share the shift
ShiftShare shareTheShift = new ShiftShare();
shareTheShift.ParentId = shiftId;
String agentUserId = serviceResource.RelatedRecordId;
// Share the record with the agent
shareTheShift.UserOrGroupId = agentUserId;
// Allow them to read
shareTheShift.AccessLevel = 'Read';
shareEntriesToCreate.add(shareTheShift);
}
}
}
}
Database.insert(shareEntriesToCreate); // can use upsert?
}
}
Did this article solve your issue?
Let us know so we can improve!

