+ Start a Discussion
Apex EstrategiaApex Estrategia 

Avoid Duplicate Case

Im Trying to create a case in one of my account if my field antecipado__c = AR.

 

And I Want to Avoid duplicate. So I Tried this:

 

trigger CriarCaseAccount_AR on Account (after update) {
    
List<Case> cases = [SELECT Id, motivo__c FROM Case WHERE motivo__c = :'Formandos AR'];
    if(cases.size() < 1)
        
    List<Account> act = [SELECT Id, antecipado__c, lab__c FROM Account WHERE antecipado__c = :'AR'];
    
    for (Account acc: Trigger.new) {
        Account oldAccount = Trigger.oldMap.get(acc.ID);
        if (acc.Antecipado__c != oldAccount.Antecipado__c || acc.Lab__c != oldAccount.Lab__c){
            if (acc.lab__c <> null && acc.Antecipado__c == 'AR') {                
                    
        Case c = new Case
              (AccountID = acc.id,
               Func_abertura_chamado__c = 'ALAN FERNANDES',
               RecordTypeID = '012U000000011yC',
               Motivo__c = 'Formandos AR',
               Prazo_para_resolucao__c = Date.today(),
               Description = 'Montagens',
               Subject = 'CP7',
               Priority = 'Médio',
               Origin = 'Interna',
               Status = 'Novo',
               Ownerid = '005U0000001KraS');
      cases.add(c);
                }
        }
    }
insert cases;
}

 Tks!!!

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
trigger CriarCaseAccount_AR on Account (after update) {
    Set<Id> hasAccountCase = new Set<Id>();
    Case[] newCases = new Case[0];
    
    for(Case record:[SELECT Id, AccountId FROM Case WHERE motivo__c = 'Formandos AR' AND AccountId IN :Trigger.new])
        hasAccountCase.add(record.AccountId);
        
    for(Account record:Trigger.new)
        if(Trigger.oldMap.get(record.id).Antecipado__c != record.Antecipado__c || Trigger.oldMap.get(record.Id).Lab__c != record.Lab__c && record.Lab__c != null && record.Antecipado__c == 'AR' && !hasAccountCase.contains(record.Id) )
            newCases.add(new Case(
                AccountID = acc.id,
                Func_abertura_chamado__c = 'ALAN FERNANDES',
                RecordTypeID = '012U000000011yC',
                Motivo__c = 'Formandos AR',
                Prazo_para_resolucao__c = Date.today(),
                Description = 'Montagens',
                Subject = 'CP7',
                Priority = 'Médio',
                Origin = 'Interna',
                Status = 'Novo',
                Ownerid = '005U0000001KraS'
            ));
    
    insert newCases;
}