function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Swaroopa Akula 2Swaroopa Akula 2 

how to auto populate the entitlement name on case

Hi I have written a trigger to get autopopulate  the entitlement name(Look up field on case) on case when the time of case creation. 

One account has 2 entitlement processes. 
trigger EntitlementAssign on Case (before insert) {
 Set<Id> accountIds = new Set<Id>();
    for (Case c : Trigger.new) {
        accountIds.add(c.AccountId);
    }
    accountIds.remove(null);
    if (!accountIds.isEmpty()) {
        Map<Id, Entitlement> entitlementMap = new Map<Id, Entitlement>();
         for (Entitlement e : [select AccountId,Name from Entitlement where AccountId in :accountIds]) {
            entitlementMap.put(e.AccountId, e);
        }

        Entitlement process = [select Name from Entitlement where Name = 'Entitlement Process Name'];
            List<Entitlement> entitlementsToInsert = new List<Entitlement>();
            for (Id id : accountIds) {
                if (entitlementMap.containsKey(id)) {
                continue;
        }
            entitlementsToInsert.add(new Entitlement(Name = 'Entitlement Name',SlaProcessId = process.Id,
                StartDate = Date.today().addDays(-1), // Start date of yesterday
                Enddate = Date.today().addDays(1), // End date of tomorrow
                AccountId = id ));
        }

        if (!entitlementsToInsert.isEmpty()) {
            insert entitlementsToInsert;
            for (Entitlement e : entitlementsToInsert) {
                entitlementMap.put(e.AccountId, e);
            }
        }
 
        for (Case c : Trigger.new) {

            if (c.AccountId == null) {
                continue;

            }

            c.EntitlementId = entitlementMap.get(c.AccountId).Id;
        }
    }

}
Swaroopa Akula 2Swaroopa Akula 2
Entitlement name is not getting populate. 
I have two entitlements on each account(Priority1 and proirity 2 ) please someone help me on how can we get the correct entitlement and populate in the case