0

Here is the code from my trigger which saves without syntax errors but gives the below error when I edit a contact.

Code

trigger AddToPG on Contact (after insert, after update) {
    List<GroupMember> GMlist = new List<GroupMember>();
    for(Contact U : Trigger.New) {
        if(U.Add_to_Group__c = TRUE) {
            GroupMember GM = new GroupMember();
            GM.GroupId = '00Gg0000000afKH';
            GM.UserOrGroupId = U.Id;
            GMList.add(GM);         
        }
    }

        insert GMList;
    }

Error

Error:Apex trigger AddToPG caused an unexpected exception, contact your administrator: AddToPG: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.AddToPG: line 4, column 1

1

Simple typo on line 4; you need == not = (or remove == TRUE altogether). Code is currently trying to set the Add_To_Group__c field of each U record.

trigger AddToPG on Contact (after insert, after update) {
    List<GroupMember> GMlist = new List<GroupMember>();
    for(Contact U : Trigger.New) {
        if(U.Add_to_Group__c == TRUE) {
            GroupMember GM = new GroupMember();
            GM.GroupId = '00Gg0000000afKH';
            GM.UserOrGroupId = U.Id;
            GMList.add(GM);         
        }
    }

        insert GMList;
    }
| improve this answer | |
  • Thanks Richard. I have changed the code but am now getting a different error. Error:Apex trigger AddToPG caused an unexpected exception, contact your administrator: AddToPG: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, User/Group ID: id value of incorrect type: 003g000000HfUsiAAF: [UserOrGroupId]: Trigger.AddToPG: line 12, column 1 I amgetting the group ID from the URL on the group detail page. any ideas? – GMan Sep 1 '14 at 11:33
  • GM.UserOrGroupId need to be a user or a group; you are trying to set this to a contact that isn't allowed (003 is the prefix for contacts). The groupId may well be correct. – Richard Durrant Sep 1 '14 at 13:10
  • I see what you mean. U.ID is trying to set the contact ID instead of User ID or group ID. Is there any way to alter my code to allow me to add a contact to a public group? The contacts will be enabled as partner users so they will have a user record if that helps? – GMan Sep 1 '14 at 13:26
  • You will need to go to the user table and look at records with a matching ContactId. You should see that any contacts that are partner users will have a matching User record linked by the Contact Id. You should then be able to do a select from the user table based on the provided contactIds. – Richard Durrant Sep 1 '14 at 16:12

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.