0

I am trying to assign tasks to a user based on their profile once the recorded is inserted into Salesforce.

The trigger is hitting an exception even though it's compiling correctly. The code is below:

trigger insertTasks on User (after insert) {
// get list of users needed to assign
List<User> userList = [SELECT Id FROM User where ProfileId = '00e4x000000m2tPAAQ' LIMIT 10];
List<Objectives__c> objList = [SELECT Id FROM 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.OwnerId = userList.get(0).Id;
        obj.Status__c = 'Not Started';
}

if(userList.size() > 0)
{
    // insert objectives into a list for the new users with the specified profile
    insert objList;
}

The error is saying that INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

The goal here is to assign a list of objectives to the new user that gets assigned the correct profile but only if they do not already have any objectives.

0

There are several problems here.

trigger insertTasks on User (after insert) {
// get list of users needed to assign
List<User> userList = [SELECT Id FROM User where ProfileId = '00e4x000000m2tPAAQ' LIMIT 10];

Never hard-code Ids. Why query 10 users when you only want one? Store the single user Id in a Custom Setting and access it dynamically.

List<Objectives__c> objList = [SELECT Id FROM Objectives__c];

You don't use this; why are you querying it? Unrestricted queries like this can get you into limits trouble very quickly.

//loop thru users in the users list created above.
for(User newUser : Trigger.new){
    //create new objectives
    Objectives__c obj = new Objectives__c();
        obj.OwnerId = userList.get(0).Id;
        obj.Status__c = 'Not Started';
}

You just threw away obj because it was never added to a collection for insert. You probably want to create a new, empty List<Objectives__c> to collect these records.

Also worth noting: these records have no relationship to newUser, so they're not going to be distinguishable from one another when multiple Users are created.

if(userList.size() > 0)
{
    // insert objectives into a list for the new users with the specified profile
    insert objList;
}
  1. You don't need to check .size() before performing DML. DML on an empty collection is a no-op.
  2. objList is not the correct variable here. That's the spurious List created above that includes every existing Objectives__c record in the database. You want to insert the new collection you create of records built in this trigger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.