0
votes

We have two standard objects account(parent) and contact (child ). i want to write a trigger to populate the lastname field of contact with the name field of account

The trigger below performs the same task but soql query is from child to parent .

I want the trigger which performs the same work but using soql query ( relationship query ) from parent to child .

trigger trgSetLastName on Contact (after insert) 
{
List<Contact> lstConUpdate = new List<Contact>();
List<Contact> lstContact = [select id,Account.Name from Contact where 
id in:  trigger.newmap.keyset()];
for(Contact con: lstContact)
{
    con.LastName = con.Account.Name;
    lstConUpdate.add(con);
}
if(lstConUpdate.size() > 0){
    update lstConUpdate;
}
}

i want a trigger for this .help

1

1 Answers

1
votes

Step 1. Build a Set<id> of Account Ids:

for (Contact c : trigger.new){
    acctIdSet.add(c.AccountId);
}

Step 2. Select related Accounts into a Map<Id,Account> using:

[SELECT {fields}
FROM Account
WHERE Id IN :acctIdSet];

Step 3. Loop through trigger.new and extract the corresponding Account from your Map.

Step 4. Update the LastName value on contact with the value on your Account - assuming it exists.

Step 5. Make your trigger fire before insert:

trigger trgSetLastName on Contact (before insert, before update)