Skip to main content
Hi there, 

At my organization we create cases based off the account. I am looking to write some code that would only allow one case per account. I have started on the below code but I keep getting some errors. Can anyone help me? 

trigger maxOneCasePerAccount on Case(after insert)

{

    // create a map of cases keyed by their account id

    Map<Id, List<Case>> casesByAccountId=new Map<Id, List<Id>>();

    for (Case c : trigger.newMap.values())

    

        {

            List<Case> casesForAccount=casesByAccountId.get(c.AccountId);

            if (null==casesForAccount)

            {

                casesForAccount=new List<Id>();

                casesByAccountId.put(c.AccountId, casesForAccount);

            }

            casesForAccount.add(c);

        }

    }

    // now get the total number of case for each account

    Set<Id> ids=casesByAccountId.keySet();

    List<AggregateResult> ars=[select AccountId, count(id) from Case where AccountId in :ids group by AccountId];    

    // now iterate the results and error anything that already has a case

    for (AggregateResult ar : ars)

    {

        Id accId=ar.get('AccountId');

        Integer caseCount=ar.get('expr0');

        if (caseCount>0)

        {

            List<Case> casesForAccount=casesByAccountId.get(accId);

            for (Case c : casesForAccount)

            {

                c.addError('Max one case per account');

            }

        }

    }

}
1 Antwort
0/9000