0

I have a parent object (Account), child object(Contract) and a grand child object(contract exceptions). Contract exceptions has master detail relationship with contract. My requirement is to fetch list of contract exception records using accountId. I want to store Id of account and corresponding contract exceptions in a map so I can use them in code. How can I achieve this using maps? Any suggestions

2
  • 1
    What have you tried? Where are you stuck?
    – Derek F
    Nov 19, 2021 at 19:35
  • Hi Derek, I have created a map for contract Id and list of contract exceptions (map <id, list<exceptions>). I am looking for a way to create a map so I can have account Id as key and get list of contract exceptions. any pointers would help. Thanks Nov 20, 2021 at 5:00

1 Answer 1

0

As I understand, Contracts object is related to Account, but ContractsException do not have any relation with Account, we have to go via Contracts. So first, we get a list of all contracts which are related to Accounts, then for every contract found,we get the list of all Contract Exception records.

list<contract> contractList = new list<contract>();
list <contractexception> contractExceptionList= new list <contractexception>();
list<id> idList = new list<id>();
map<id, list<contractexception>> ContractExceptionMap = new map<id, list<contractexception>>();

contractList= [select id, name, accountid from contract where accountID!=null];
contractExceptionList = [select id, name from contractexception where contactID=:contractList];

for (Contractexception contr: contractExceptionList)
{
    if (ContractExceptionMap.containskey(contr.contactID))
    {
        ContractExceptionMap.get(contr.contactID).add(contr);
    }
    else
    {
        ContractExceptionMap.put(contr.contactID, new list<contractexception> {contr}); 
    //this creates a map of all contracts which are related to account by contractID and Contract obj as key-value
    }
}

map<id, list<contractexception>> AccContractExceptionMap = new map<id, list<contractexception>>();
for (contract contr: contractList)
{
    for (ID idloop:ContractExceptionMap.keyset() )
    {
        if (idloop== contr.id)
        {
            AccContractExceptionMap.put(contr.accountid, ContractExceptionMap.get(idloop) );
        }
    }
}
    //this creates a map of contract Account IDs and related contract exception records

You must log in to answer this question.

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