[SalesForce] How to change the permission sets via Apex

On Account Object there is a lookup field callled as 'AccountManager' where I can assign the user(Lookup(User)).
Now there is a tab called as "Account Team "(Under the Account) where I can add multiple users which I can modify.
Suppose A is the user who creates an account then he can add and modify the "Account Team " members.
and in the 'AccountManager'field if I add the user as 'B'.when I login to the application as B and navigating to the perticular account that was created by A then B can see the Account Team Member(Read Only) but can not add or delete it.

I have a requirement inwhich if any user who creates an account and add the user in 'AccountManager' field then Account Manager should modify the team members.

I know with manually it is possible but i am looking for a programatical way like writing an apex class then call its method in trigger.
It would be better if I get any example

I am new in Apex Programming &Following code I am trying to write

public with sharing class AssignPermissionSet{

   public static void assignPermission(List<PermissionSetAssignment> preset ){
   //List<Account> Acc=[Select id, name, type,AccountManager__c, RecordType.Name FROM Account WHERE RecordType.Name ='Account Group'];
     List<PermissionSet> per=[SELECT Id,Name, PermissionsModifyAllData FROM PermissionSet];

     List<User> u=[select id,name from user where id IN (select AccountManager__c from Account) ];
 preset=[ SELECT AssigneeId,Id,PermissionSetId,PermissionSet.Name FROM PermissionSetAssignment where AssigneeId =:u AND PermissionSetId =:per];

     List<ObjectPermissions> op = [SELECT Id,ParentId,SobjectType,PermissionsRead,PermissionsEdit,PermissionsDelete,PermissionsCreate FROM ObjectPermissions where SobjectType='Account' AND ParentId=:per ];        

This is just a rough code I am trying to write.
need a help how how to update the existing Permission Set where I can assign Create,Delete,edit permission to the Account Manager user.In our application every user must have at least one permission sets.

Best Answer

This approach you are suggesting will not work as you are talking about record level access and not object level. This mainly has to do with the Org wide defaults and sharing settings.

You would need to create the AccountShare object and provide read/write access to the Account Manager for the record in context. He can then modify the Account Team Members.

AccountShare share = new AccountShare();
share.AccountId = '<yourAccountId>';

//Set the user Id to share the accounts with
share.UserOrGroupId = '<AccountManagerId>';

share.OpportunityAccessLevel = 'Edit';
share.CaseAccessLevel = 'Edit';
Related Topic