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
SIVA KUMAR 507SIVA KUMAR 507 

hey guys please help me!!! i need trigger code urgently

1. Create Accounts - Google, Amazon, StackNexus
2. These accounts will have website field values as google.com, amazon.com, stacknexus.io
3. Create contacts in bulk using the execute anonymous window
- The contacts created should have email ids from these three company domains
- for example test@google.com, test1@amazon.com, test2@stacknexus.io, test3@google.com
- create these using for loop
4. In the trigger, the contacts should be assigned the accounts which match the website with the email domain
5. all these should be bulkified

Thanks in advance,
siva kumar reddy
ShivankurShivankur (Salesforce Developers) 
Hi Siva Kumar,

You can use something like below in your trigger on Contact:
trigger DomainTriggerHandler on Contact (before insert) {
    Set<String> emailDomains = new Set<String>();

    for (Contact con : Trigger.New) {
        if (con.Email == null) {
            continue;
        }   

        emailDomains.add(con.Email.split('@').get(1));
    }

    emailDomains.remove(null);
           
    if (!emailDomains.isEmpty()) {
        Map<String, Account> emailDomainToAccountMap = new Map<String, Account>();

        for (Account a : [ 
            select Website,
                OwnerId
            from Account
            where Website in :emailDomains
        ]) {
            emailDomainToAccountMap.put(a.Website, a);
        }   

        for (Contact con : Trigger.New) {
            if (con.Email == null) {
                continue;
            }

            String domain = con.Email.split('@').get(1);

            if (!emailDomainToAccountMap.containsKey(domain)) {
                continue;
            }

            con.OwnerId = emailDomainToAccountMap.get(domain).OwnerId;
        }
    }
}

Hope above information helps, Please don't forget to mark as Best Answer so that it can help others in the future.

Thanks.
SIVA KUMAR 507SIVA KUMAR 507
Hi Shivankur,
this code trigger code is not working....please make any changes.