When a new user is created in Salesforce and matches a custom field named Role__c, I am trying to take a list of objectives__c and apply them to the user. I want to copy everything from the objective__c and create the same objective again, but with this user as the owner.
Can that be done? Here is a basic sample code that I have so far.
trigger insertTasks on User (after insert) {
// get list of users needed to assign
List<User> userList = [SELECT Name FROM User where Onboarding__c = true];
List<Objectives__c> masterList = [SELECT Id,Name,Duration__c,Minutes__c,OwnerId,URL__c, Week__c FROM Objectives__c];
List<Objectives__c> objList = new List<Objectives__c>();
//loop thru users in the users list created above.
for(User newUser : Trigger.new){
//create new objectives
Objectives__c obj = new Objectives__c();
obj.Name = obj.Name;
obj.Status__c = 'Not Started';
objList.add(obj);
}
if(userList.size() > 0)
{
// insert objectives into a list for the new users with the specified profile
insert objList;
}
The goal is to have all of the fields that are populated in the masterList to be added to the user that has onboarding checked on the creation of the user.
I was able to get closer at this time but am now getting the error below:
First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Objectives__c, original object: User: []: Trigger.insertTasks: line 18, column 1