You need to sign in to do that
Don't have an account?

Create group through apex
Hi All,
I want to share a opportunity through apex code and
i tried to set role id as userid or group id.. but its throwing a error like Database.Error[getFields=(UserOrGroupId);getMessage=User/Group ID: id value of incorrect type: 00EV0000000Hp7wTAP;getStatusCode=FIELD_INTEGRITY_EXCEPTION;]
so i planned to create a group and add members belongs to that role.. after creating group i can set the group id while sharing opportunity.
i need to create a group and add few members in a group through apex code,
am not getting how to create group and add members through apex code.
Please give me a solution...
Thanks in advance.. :)
Hi,
Please post your code, so that we can debug and make that working..
Here is the Code.............
//Create Groups
public string groupName;
groupName='opportunityGroup';
Id groupId;
Group groupsExisting = new Group([Select Id, Name From Group where Name=:groupName LIMT 1]);
list<GroupMember> listGroupMembersToInsert= new list<GroupMember>();
if(groupsExisting ==null){
Group newGroup = new Group();
newGroup.Name = groupName;
newGroup.DoesIncludeBosses = false;
//Insert New Group for Opp Sharing
insert newGroup;
groupId=newGroup.Id;
}else{
groupId=groupsExisting.Id;
}
for(Opportunity Opp: Trigger.new){
list<User> Det= [Select u.UserRoleId, u.Id From User u where u.Contact.AccountId =: Opp.AccountId];
GroupMember newMember=new GroupMember();
newMember.GroupId=groupId;
newMember.UserOrGroupId=Det.Id;
listGroupMembersToInsert.add(newMember);
OppShare.add(new OpportunityShare(UserOrGroupId =groupId,
OpportunityId = Opp.Id,
OpportunityAccessLevel = PermissionLevel));
}
//Insert Group Members
if(!listGroupMembersToInsert.IsEmpty()){
insert listGroupMembersToInsert;
}
List<Database.Upsertresult> lsr0 = Database.upsert(OppShare, false);
Integer newcnt0=0;
for(Database.UpsertResult sr0:lsr0){
if(!sr0.isSuccess()){
Database.Error emsg0=sr0.getErrors()[0];
system.debug('\n\nERROR ADDING SHARING:'+OppShare[newcnt0]+'::'+emsg0);
}
newcnt0++;
}
Please mark this aswere is solution if you find this is useful