Intro
In this page you can find Apex Templates for Deployment Tasks of type Apex.
Use these templates as a starting point of your Apex script automations. Contributing to these or mentioning bugs in the templates is highly appreciated.
Make sure your final Apex Script aligns with the Development Guidelines.
Templates
Scheduling Job
//Schedule JobDemo apex class to run every day at midnight. Scheduled Job will be named Job Demo
System.schedule('Job Demo','0 0 * * * ?', new JobDemo());
Aborting Scheduled Job
// Abort Scheduled Job named Job Demo
List<CronJobDetail> cronJobDetails = [SELECT Id FROM CronJobDetail WHERE Name='Job Demo'];
Id detailId = cronJobDetails.isEmpty() ? null : cronJobDetails.get(0).Id;
if (detailId != null) {
Id jobId = [SELECT Id FROM CronTrigger WHERE CronJobDetailId = :detailId][0].Id;
System.abortJob(jobId);
}
Update Hierarchy Custom Setting update for Profile, depending on Org
The following example is upserting custom setting for profile System Administrator. It supports identyfing environment by name, therefore we can assign different values for each.
String currentEnvironmentName = System.DomainParser.parse(URL.getOrgDomainUrl()).getSandboxName();
currentEnvironmentName = String.isBlank(currentEnvironmentName) ? 'prod' : currentEnvironmentName;
Profile sysAdminProfile = [Select Id from Profile WHERE Name = 'System Administrator' LIMIT 1];
ExampleCustomSetting__c customSett = ExampleCustomSetting__c.getInstance(sysAdminProfile.Id);
Boolean doUpdate = true;
if (currentEnvironmentName.equalsIgnoreCase('UAT')) {
customSett.ExampleField1__c = '12345';
} else if (currentEnvironmentName == 'prod') {
customSett.ExampleField1__c = '67890';
} else {
doUpdate = false;
}
if (doUpdate) {
upsert customSett;
System.debug('Update done for record', customSett);
}
Update List Custom Setting records
The following example is upserting custom setting for profile System Administrator. It supports identyfing environment by name, therefore we can assign different values for each.
Map<String, ExampleCustomSetting__c> customSettings = ExampleCustomSetting__c.getAll();
for (ExampleCustomSetting__c setting : customSettings.values()) {
if (setting.Name == 'ExampleName1') {
setting.CustomField1__c = 'UpdatedValue1';
} else if (setting.Name == 'ExampleName2') {
setting.CustomField2__c = 'UpdatedValue2';
}
}
update customSettings.values();
System.debug('Custom settings updated successfully.');
Update List Custom Setting records - ONLY Org Default
ExampleCustomSetting__c orgDefaultSetting = ExampleCustomSetting__c.getOrgDefaults();
if (orgDefaultSetting != null) {
orgDefaultSetting.CustomField1__c = 'UpdatedOrgDefaultValue1';
orgDefaultSetting.CustomField2__c = 'UpdatedOrgDefaultValue2';
update orgDefaultSetting;
System.debug('Org default custom setting updated successfully.');
} else {
System.debug('No org default custom setting exists.');
}
Update Custom Metadata Type Record/s Depending on Org
Note: Apex script is only necessary if the custom metadata type record has specific values depending on the Org. If the CMDT record is the same for all orgs, perform a standard commit as any other metadata change, the apex script would not be necessary in this scenario.
String currentEnvironmentName = System.DomainParser.parse(URL.getOrgDomainUrl()).getSandboxName();
currentEnvironmentName = String.isBlank(currentEnvironmentName) ? 'prod' : currentEnvironmentName;
/*
!! BEFORE RUNNING
Replace ExampleCustomMetadataType__mdt with the API name of your Custom Metadata Type
Replace 'Record_DeveloperName' with the DeveloperName of the record you want to update
*/
ExampleCustomMetadataType__mdt recordToUpdate = [
SELECT DeveloperName, CustomField1__c, CustomField2__c
FROM ExampleCustomMetadataType__mdt
WHERE DeveloperName = 'Record_DeveloperName'
LIMIT 1
];
Boolean doUpdate = true;
if (currentEnvironmentName.equalsIgnoreCase('UAT')) {
recordToUpdate.CustomField1__c = 'UpdatedValueUAT1';
recordToUpdate.CustomField2__c = 'UpdatedValueUAT2';
} else if (currentEnvironmentName == 'prod') {
recordToUpdate.CustomField1__c = 'UpdatedValueProd1';
recordToUpdate.CustomField2__c = 'UpdatedValueProd2';
} else {
doUpdate = false;
}
if (doUpdate) {
Metadata.DeployContainer container = new Metadata.DeployContainer();
container.addMetadata(recordToUpdate);
Id deployId = Metadata.Operations.enqueueDeployment(container, null);
System.debug('Deployment ID: ' + deployId);
}
Permission Sets Assignment for Active users with Exceptions
The following example is upserting custom setting for profile System Administrator. It supports identyfing environment by name, therefore we can assign different values for each.
/*
!! BEFORE RUNNING
Update 'permissionSetsToAssign' list below by adding the permission sets to assign to all active users
*/
List<String> permissionSetsToAssign = new List<String>{'PermissionSetExampleName'};
Map<String, Id> permissionSetsIdsMappedByName = new Map<String, Id>();
for (PermissionSet permSet : [SELECT Id, Name FROM PermissionSet WHERE Name in : permissionSetsToAssign]) {
permissionSetsIdsMappedByName.put(permSet.Name, permSet.Id);
}
List<PermissionSetAssignment> assignmentsToInsert = new List<PermissionSetAssignment>();
/*
!! BEFORE RUNNING
In the Filter of the query, include the users for which the permission set should NOT be asigned
*/
List<User> activeUsers = [
SELECT Id, UserRole.DeveloperName,
(
SELECT Id, PermissionSetId, PermissionSet.Name
FROM PermissionSetAssignments
WHERE PermissionSetId != null
)
FROM User
WHERE IsActive = true
AND Name NOT IN ('Platform Integration User', 'Data.com Clean')
];
for (User user : activeUsers) {
Set<String> assignedPermSetsNames = new Set<String>();
for (PermissionSetAssignment assignment : user.PermissionSetAssignments) {
assignedPermSetsNames.add(assignment.PermissionSet.Name);
}
for (String permSetName : permissionSetsToAssign) {
if (!assignedPermSetsNames.contains(permSetName)) {
PermissionSetAssignment assignment = new PermissionSetAssignment(
AssigneeId = user.Id,
PermissionSetId = permissionSetsIdsMappedByName.get(permSetName)
);
System.debug(LoggingLevel.ERROR, assignment);
assignmentsToInsert.add(assignment);
}
}
}
if (!assignmentsToInsert.isEmpty()) {
System.debug('There are ' + assignmentsToInsert.size() + ' assignments to be created.');
List<DAtabase.SaveResult> result = DAtabase.insert(assignmentsToInsert, false);
for (Database.SaveResult res : result) {
if (!res.isSuccess()) {
System.debug(JSON.serialize(res.errors));
}
}
}
Permission Sets Assignment for Users with Specific Profile
This is an example variation of the previous script
/*
!! BEFORE RUNNING
1. Update below variable permSetName with an API Name of permission set that should be assigned to all active users with any of specified profiles.
If the permission set is not found in system, exception of type PermSetNotFoundException will be thrown
2. In the variable profileNames provide list of profiles. Only active users with those profiles will be updated.
*/
String permSetName = 'Permission Set API Name';
List<String> profileNames = new List<String> {
'Name of Profile 1',
'Name of Profile 2',
'[...]'
};
List<PermissionSet> permSetResult = [SELECT Id, Name FROM PermissionSet WHERE Name = :permSetName];
if (permSetResult.isEmpty()) {
throw new PermSetNotFoundException('There is no permission set with api name ' + permSetName);
}
PermissionSet permSet = permSetResult.get(0);
List<PermissionSetAssignment> assignmentsToInsert = new List<PermissionSetAssignment>();
List<User> activeUsers = [
SELECT Id, UserRole.DeveloperName,
(
SELECT Id, PermissionSetId, PermissionSet.Name
FROM PermissionSetAssignments
WHERE PermissionSetId = :permSet.Name
)
FROM
User
WHERE
IsActive = true
AND
Profile.Name IN :profileNames
AND
Id NOT IN (
SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSet.Name = :permSetName
)
];
for (User user : activeUsers) {
if (user.PermissionSetAssignments.isEmpty()) {
PermissionSetAssignment assignment = new PermissionSetAssignment(
AssigneeId = user.Id,
PermissionSetId = permSet.Id
);
System.debug(LoggingLevel.ERROR, assignment);
assignmentsToInsert.add(assignment);
}
}
if (!assignmentsToInsert.isEmpty()) {
System.debug('There are ' + assignmentsToInsert.size() + ' assignments to be created.');
insert assignmentsToInsert;
} else {
System.debug('All users already have an assignment to permission set ' + permSetName);
}
public class PermSetNotFoundException extends Exception {
//exception
}
Permission Set Group Assignment by Profile
Map<String, Id> permissionSetGroupsIdsMappedByDevName = new Map<String, Id>();
for (PermissionSetGroup permSetGroup : [SELECT Id, DeveloperName FROM PermissionSetGroup]) {
permissionSetGroupsIdsMappedByDevName.put(permSetGroup.DeveloperName, permSetGroup.Id);
}
List<PermissionSetAssignment> assignmentsToInsert = new List<PermissionSetAssignment>();
Map<String, String> profileNameToPermSetGroupDevNameMap = new Map<String, String> {
'Profile Name 1' => 'Permission Set Group API Name 1',
'Profile Name 2' => 'Permission Set Group API Name 2',
'Profile Name 3' => 'Permission Set Group API Name 3'
};
List<User> usersWithoutAssignments = new List<User>();
for (String profileName : profileNameToPermSetGroupDevNameMap.keySet()) {
usersWithoutAssignments.addAll([
SELECT Id, Name, Profile.Name
FROM User
WHERE
IsActive = true AND
Profile.Name = :profileName AND
Id NOT IN (
SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSetGroup.DeveloperName = :profileNameToPermSetGroupDevNameMap.get(profileName)
)
]);
}
for (User usr : usersWithoutAssignments) {
PermissionSetAssignment assignment = new PermissionSetAssignment(
AssigneeId = usr.Id,
PermissionSetGroupId = permissionSetGroupsIdsMappedByDevName.get(profileNameToPermSetGroupDevNameMap.get(usr.Profile.Name))
);
System.debug(LoggingLevel.ERROR, assignment);
assignmentsToInsert.add(assignment);
}
System.debug('There are ' + assignmentsToInsert.size() + ' assignments to be created.');
if (!assignmentsToInsert.isEmpty()) {
insert assignmentsToInsert;
}
Creating a User
String profileName = 'Standard User';
Profile userProfile = [SELECT Id FROM Profile WHERE Name = :profileName LIMIT 1];
User newUser = new User(
FirstName = 'John',
LastName = 'Doe',
Email = 'johndoe@example.com',
Username = 'johndoe@example.com',
Alias = 'jdoe',
TimeZoneSidKey = 'America/New_York',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
ProfileId = userProfile.Id,
ExampleCustomField__c = 'Example Value',
IsActive = true
);
insert newUser;
System.debug('User created successfully: ' + newUser.Id);
The best way to get IT support is to use the new
Service One Platform.