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
ishaan singh dhillonishaan singh dhillon 

Help with count of records in trigger on Case object

I am trying to write a trigger on Case object where I am trying to retreive the number of how many contacts have the same email as the email from which the case has originated in the web-to-case scenario. But I am getting the error on the first line itself, the error msg is :

Error: Compile Error: Unexpected token '='. at line 3 column 53

I know the code might not be perfect as I am still learning so I am seeking help, the following is the code I have till now:
trigger CountContact on Case (before insert) 
{
    Case.Count_of_Records_with_Web_email_address__c = [select count() from Contact where Contact.Email = Case.SuppliedEmail];
    
    if (Case.Count_of_Records_with_Web_email_address__c > 1)
    {
        return;
    }
    Else
    {
        Contact Cont = [select Contact from Contact where Contact.Email = Case.SuppliedEmail];
        Case cas;
        cas.Email = Cont.Email;
        cas.Account = Cont.Account;
    }
}

Thanks in advance.

Regards.
Best Answer chosen by ishaan singh dhillon
MKRMKR
Hi,

You can only access the inserted cases with Trigger.New variable. Try this:
 
trigger CountContact on Case (before insert) 
{
    Map<String, List<Contact>> suppliedEmails = new Map<String, List<Contact>>();
    for(Case createdCase : Trigger.New) {
        suppliedEmails.put(createdCase.SuppliedEmail, new List<Contact>());
    }
    
    //Create map from supplied email to matching contacts
    for(Contact existingContact : [SELECT Id, Email, AccountId FROM Contact WHERE Email IN :suppliedEmails.keySet()]) {
        suppliedEmails.get(existingContact.Email).add(existingContact);
    }

    //Populate data from contacts to cases
    for(Case createdCase : Trigger.New) {
        
        //Populate data only if just one contact is found
        if (suppliedEmails.get(createdCase.SuppliedEmail).size() == 1) {
             Contact onlyMatchingContact = suppliedEmails.get(createdCase.SuppliedEmail).get(0);
             createdCase.ContactId = onlyMatchingContact.Id;
             createdCase.AccountId = onlyMatchingContact.AccountId;
        }
    }

}

Regards,
MKR​​​​​​​