I am getting an error on the groupId get statement. This is my first attempt to use maps. Can someone tell me what I am doing wrong?


trigger UserPublicGroupMembership on User (after insert, after update ) {

    List<GroupMember> gpMember = new list<GroupMember>();

    List<Group> pubGroup = new list<Group>([
        Select Id,Name 
        FROM Group
    Map<Id, Group> gmap = new Map<Id, Group>(pubGroup);

    //Put user in group if insert
        for(User u:trigger.new){

            IF (u.UserRole.Name == 'BCS Manager'){
                gpMember.add(new GroupMember(
                    UserOrGroupId = u.Id,
                    GroupId = gmap.get('BCS Managers')

            //so on and so on for all our roles. 

    //Check if profile or role changed, then put user in group if true


    //Nnow that list is populated insert. 
    //Always doing an insert as system doesn't care about existing membership conflicts. 
    Insert gpMember;


Error Message:

Invalid initial expression type for field GroupMember.GroupId, expecting: Id

1 Answer 1


When you call gmap.get(...) it gives you back a Group. You need its Id instead, so use gmap.get(...).Id.

If you're not sure the record will exist, this pattern can cause a QueryException. In that case, it might be better to guard against such a case:

Group bcsGroup = gmap.get('BCS Managers');
if (bcsGroup != null)
    // intermediate logic
    GroupId = bcsGroup.Id

Also, note that you don't need to use so much boilerplate when performing queries. Just do:

List<Group> groups = [/*query*/];

Or if you just need the Map:

Map<Id, Group> gropus = new Map<Id, Group>([/*query*/]);
  • @Matt glad I could help.
    – Adrian Larson
    Aug 31, 2016 at 16:58
  • @Matt Don't forget, if this answer addressed your problem, to please consider accepting it by clicking on the check mark/tick to the left of the answer, turning it green. This marks the question as resolved to your satisfaction, and awards reputation both to you and the person who answered.
    – Adrian Larson
    Aug 31, 2016 at 17:45
  • 1
    yah sorry I meant to do that. You responded so fast with your answer I was within the time limit to accept your answer as best. I did it now.
    – Matt M
    Sep 1, 2016 at 17:13

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.