0

I am trying to get values from map and assign the value in trigger. Below is the code so far -

I need to get ID based on a value from a Map which I have created.

public class AccountTriggerHandler externds TriggerHandler {    
    protected override void afterInsert() {
        List<Account> lstAcc = (List<Account>)Trigger.new;

        // Map of ID and Account Role
        Map<Id, Account_Role__c> accRoleMap = new Map<Id, Account_Role__c>();
    
        //Get all roles
        List<Account_Role__c> accRoles= [Select ID, Role__c from Account_Role__c]
        for (Account_Role__c role: accRoles) {
            accRoleMap.put(role.Id, role);
        }

        //Get role ID for each role name in the trigger
        for(Account acc: lstAcc) {
            // Get role name from trigger
            String roleName = acc.Role_Name__c;
            // Get role ID based on Name from accRoleMap
            Id roleId = accRoleMap.get(roleName).Id; // This does not fetch the ID for the specific role.
        }
    }
}

1 Answer 1

1

create your map using the role's name instead of Role's Id.

// Map of Role Name and Account Role
Map<String, Account_Role__c> accRoleMap = new Map<String, Account_Role__c>();

//Get all roles
List<Account_Role__c> accRoles= [Select ID, Name, Role__c from Account_Role__c]
for (Account_Role__c role: accRoles) {
    // using role.Name as key, or whatever field that matches the value on acc.Role_Name__c
    accRoleMap.put(role.Name, role);
}

Hope it helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .