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
Chitral ChaddaChitral Chadda 

trigger to populate parent field from child object using relationship query from "parent to child"

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
bob_buzzardbob_buzzard
You can't really query from parent to child, as its a one-to-many relationship.  You can query back all of the child contacts for an account, but I'm not sure that helps you much.

The trigger you have posted does what you require - can you tell us why you need another version?
Chitral ChaddaChitral Chadda
cos i have to do it the other way "learn" there might be some way out for this .
bob_buzzardbob_buzzard
You can't do it in a contact trigger, it doesn't make sense to go via the account to get the details you already have.  Can you tell us a bit more about the use case?  Why do you have to do it the other way?
Chitral ChaddaChitral Chadda
jus for learning sake . there might b some way out to do this
Deepak Kumar ShyoranDeepak Kumar Shyoran
To fetch child records from a Parent you need inner query which will return you all Contact assiciated with a particular Account and then you can easily update those contacts.

Use below code it will solve your problem.
List<Contact> conToUpdate = new List<Contact>() ;

for(Account acc : [Select id,Name,(Select id,LastName from Contacts) from Account where Id in: trigger.newmap.keyset() ] ) {
    
    for(Contact con : acc.Contacts) {
        con.LastName = acc.Name ;
        conToUpdate.add(con) ;
    }
}

if(conTOUpdate.size() > 0)
    update conTOUpdate ;

Please mark my answer as a best solution to your question to help others if it solves your problem.
Chitral ChaddaChitral Chadda
trigger trgLastName on Contact (after insert)

{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select id,Name,(Select id,LastName from Contacts) from Account where Id in: trigger.newmap.keyset() ] )
  {
     for(Contact con : acc.Contacts)
     {
     con.LastName = acc.Name ;
     conToUpdate.add(con) ;
     }
  }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}



when i save the contact  the , lastname is not changed it remains the same  like if i put account name as  "ab".
when i go to contact and put lastname as "cd" on saving it . It remains "cd ",and not "ab"
Deepak Kumar ShyoranDeepak Kumar Shyoran
This is because you wrote this trigger on Contact Not on Account ,  I think you requirement was to Update the LastName of Contact whenever a Account name is Updated and also when a new contact is inserted , the above is to do the first part whenever a Account is updated, so please write this trigger on Account 
trigger trgLastName on Account(after insert)

{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select id,Name,(Select id,LastName from Contacts) from Account where Id in: trigger.newmap.keyset() ] )
  {
     for(Contact con : acc.Contacts)
     {
     con.LastName = acc.Name ;
     conToUpdate.add(con) ;
     }
  }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}
And to update LastName of Contact when a new Contact is insert use you previous code in following way.

trigger trgSetLastName on Contact (before insert) {

    for(Contact con: [select id,Account.Name from Contact where id in: trigger.newmap.keyset()){
        con.LastName = con.Account.Name;
    }
}

You have to write two trigger one is on Account and Second on Contact to acheive this.

Please mark my answer as a best solution to your question and Like it to help others if it solves your problem.
Chitral ChaddaChitral Chadda
i deleted all my trigger  and saved both of these .
again the same issue lastname is not changed with the acoount name .
if lastname i save "ab"  and account name is "ac"

on saving the contact the lastname remains the same  "ab" , dosent change to "ac"


  
Chitral ChaddaChitral Chadda
?

Chitral ChaddaChitral Chadda
@ deepak ... my requirement is   that when i save the  contact ,   the lastname of contact should be changed  with the name of account (parent  object)


like initially if i save  lastname of conatct as "a"  and account name is saved as " b" .... after  saving the contact the last name should be changed to "b".

Deepak Kumar ShyoranDeepak Kumar Shyoran
Have you tried the Trigger on Account for (After Update ) and also for Trigeer on Contact for After Update and After Insert. Please try these with small modification according to your if needed and let me know if still not able to get it.

Chitral ChaddaChitral Chadda
Not working again i tried I want trigger on contact gor this work :/
bob_buzzardbob_buzzard
It reallty doesn't make sense to have a trigger on contact then access the parent account just to get the contact details again. All you are learning is the wrong way to access data.
Chitral ChaddaChitral Chadda
Problem solvedd thnku all Trigger.new insub query we should write
Chitral ChaddaChitral Chadda
I know Buddy i did from child to parent I wanted to do it using parent to child Its accomplished now All ur ppl support :())
Deepak Kumar ShyoranDeepak Kumar Shyoran
Please mark your question as solved by selecting a best solution to your question.
Chitral ChaddaChitral Chadda
trigger trgset on contact (after insert)

{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  ] )
     {
     for(Contact con : acc.Contacts)
     {
     con.LastName = acc.Name ;
     conToUpdate.add(con) ;
     }
    }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}
Chitral ChaddaChitral Chadda
deppak this was the change i made .... the code set up by you.:))
Chitral ChaddaChitral Chadda
how can i restrict the code for a particular account only ...like if ther are 1000 account it will pick all ..how do i restrict it for a particular account ... in the suquery
is this right ??
for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  wher account.id==contact.id] )
Deepak Kumar ShyoranDeepak Kumar Shyoran
To fetch all Contact for a Account use below code.

[Select Name,(Select id ,LastName from Contacts ) from Account  where account.id=='xxxxxxxxx' ]

you can modify Where Condition for Account according to your need .

and if you want some more filter on your Inner Query then you can put those in following way

[Select Name,(Select id ,LastName from Contacts where LastName = 'Test Name'  Limit 10) from Account  wher account.id=='xxxxxxxxx' ] ;

hope it'll help you.

I think code witter by you is "for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  where account.id==contact.id] )" is Comparing Contact id with Account Id (please check).


Please mark my answer as a best solution to your question to help others if it solves your problem.

Ankit Gupta SFDCLearnerAnkit Gupta SFDCLearner
trigger changeLastnameOfContact on Contact (after insert)
{
    set<id> accSet=new set<id>();
    List<Contact> conToUpdate = new List<Contact>() ;
    if (Trigger.isAfter)
    {
        if (Trigger.isInsert) 
        {
            system.debug('<<<<<<<<<trigger isInsert>>>>>>>: '+ Trigger.new);
            for(Contact cnct:Trigger.new)
            {
                if(cnct.AccountId!=null)
                {
                    accSet.add(cnct.AccountId);
                }
            }
            system.debug('accSetId: '+ accSet);
    
            List<contact> conList = new List<contact>();
            List<Account> accList = new List<Account>();  
            
            IF(accSet <> null && accSet.size() > 0)
            {
            
                accList =  [select id, name from account where id in:accSet];
                 
                system.debug('accList: '+ accList);
                 
                
                    
                    for(Contact cnct:trigger.new)
                    {
                        for(Account accnt:accList)
                        {
                         
                            Contact cntObj = new Contact();
                            cntObj.id = cnct.id;
                             
                            cntObj.LastName = accnt.name +'--' + cnct.LastName;
                            
                            conToUpdate.add(cntObj) ;
                         
                        
                        }
                    }
                }
            system.debug('conTOUpdate: '+ conTOUpdate);
            if(conTOUpdate.size() > 0)
            {
               update conTOUpdate ;
            } 
        }
        
        
    }
    
    
}