+ Start a Discussion
Sure91Sure91 

trigger to update child record on basis of parent record value

Hi Guys,

I am new to salesforce and coding, need your help on below query:

I want to write a trigger to update the child record on the basis of parent record.

Parent Object: Account
Field: External_system__c

Child Object(Custom object): Classification__c
Field:Business_Status__c

Whenever a account is created with external_system__c=123 then the classification Business_Status__c should get updated to 'Active' and it should run only once on classification creation time.

Any help will be highly appreciated!!
Best Answer chosen by Sure91
Deepali KulshresthaDeepali Kulshrestha
Hi,

//Trigger on clasification__c object to populate its field when inserted.
trigger Trigg on Classification__c (Before  insert) {
    //Set to get the account id's of the "Classification__c" object.
    Set<Id> ids=new Set<Id>();
    for(Classification__c cla:Trigger.new){
        if(cla.Account_Name__c !=null){
            ids.add(cla.Account_Name__c);  
        }
    }
    
    //Map contains the id of account as key and Value as the value in "External_system__c" field. 
    Map<Id,String> mMap=new Map<Id,String>();
    //Retrieving all the account associated with "Classification__c" object .
    List<Account> accList=new List<Account>();
    accList=[select name,External_system__c from Account where Id in:ids];
    
    //Filling the map with values.
    for(Account ac:accList){
        mMap.put(ac.Id,ac.External_system__c);
    }
    
    //Iterating over the values in the Trigger.New
    for(Classification__c cla:Trigger.new){
      //getting the value from map  where key is accountId of "cla" instance of  "Classification__c" object 
   //here "mMap.get(cla.Account_Name__c)" will return value in field "External_system__c" of account associated with "cla" instance of Classification__c object. 
        if(mMap.get(cla.Account_Name__c)=='123'){
           //populating the value to true if field in the account "External_system__c" associated with the instance of clasification__c object. 
           cla.Business_Status__c=true;
        }
    }
}
I hope you find the above solution helpful. Please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha

All Answers

Sunil KhuwalSunil Khuwal
Using after trigger and new query, with the existing Classification__c record this can be done.
 
Sure91Sure91
Hi Sunil,

Thanks for your reply.

I need exact code or sample of it as I am new to coding I am unable to make it.
NitishNitish
Hi Suresh,

If you are inserting Parent record then on time of Parent record creation how you are inserting child record.

Thanks,
Nitish
Deepali KulshresthaDeepali Kulshrestha
Hi Suresh,

Please try this code:
As you need to update fields of the child record you are required to use Before Insert on your custom object "Classification__c".

trigger Trigg on Classification__c (Before  insert) {
    //It will hold the id's of account associated with  "Classification__c".
    Set<Id> ids=new Set<Id>();
    for(Classification__c cla:Trigger.new){
        if(cla.Account__c !=null){
            ids.add(cla.Account__c);  
        }
    }
    Map<Id,Decimal> mMap=new Map<Id,Decimal>();
    List<Account> accList=new List<Account>();
    accList=[select name,External_system__c from Account where Id in:ids];
    for(Account ac:accList){
        mMap.put(ac.Id,ac.External_system__c);
    }
    for(Classification__c cla:Trigger.new){
        if(mMap.get(cla.Account__c)==123){
            system.debug(':::'+cla.Account__r.External_system__c);
            cla.Business_Status__c=true;
        }
    }
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha 
Sure91Sure91
Hi Deepali,

Thanks for your help!. However I am getting "Variable does not exist: Account__c" error 
Sure91Sure91
Hi Nitish,

We are using Integration tool to load data so when accounts data is loaded automatically classification is created through batch.
NitishNitish
Hi Suresh,

Please try the below code. It might help or let me know if you will face any specific issue
Trigger AccountTrigger on Account(After insert){

	if(Trigger.isAfter && Trigger.isInsert){
		List<Id> accList=new List<Id>()
		for(Account acc:Trigger.new){
			if(acc.External_system__c == '123'){
				accList.add(acc.Id);
			}
				
		}

		List<Classification__c> claList=[SELECT Id, Business_Status__c FROM Classification__c WHERE Id in : accList];
		List<Classification__c> claListToUpdate=new List<Classification__c>;
		for(Classification__c cl:claList){

				cl.Business_Status__c='Active';
				claListToUpdate.add(cl);
		}

		if(claListToUpdate.size() != 0){
			update claListToUpdate;
		}


	}
}

Thanks,
Nitish​​​​​​​
Sure91Sure91
Hi Nitish,

I am getting error:

Error on line 5: Missing ';' at 'for' 
Error on line 13: Unexpected token ';'.

I have one doubt as well. We need to update classification object, then why trigger is on account?

Thanks & Regards,
Suresh
Deepali KulshresthaDeepali Kulshrestha
Hi Suresh,

For this I have created a lookup field having api name  as "Account__c" on the custom Object "Classification".

You can have a better view and understanding with the help of the image provided below:

User-added image

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
NitishNitish
Hi Suresh,

Sorry I got confused in scenario. Please try the below code now. It worked for me.
Trigger ClassificationTrigger on Classification__c(before insert){

	Set<Id> accIds=new Set<Id>();
	if(Trigger.isInsert && Trigger.isAfter){

		for(Classification__c cl:Trigger.new){
			if(cl.accountId !=null){
				accIds.add(cl.accountId){

				}
			}
		}

		Map<Id,Account> accMap=new Map<Id,Account>([SELECT Id,Industry From Account WHERE Id in : accIds]);

		for(Classification__c clNew:Trigger.new){
			if(accMap.get(clNew.AccountId).External_system__c=='123'){
                clNew.Business_Status__c='Active';
              
            }
		}
		
	}
}

Thanks,
Nitish​​​​​​​
Sure91Sure91
Hi Nilesh,

Sorry again, I am getting error (Variable does not exist: accountId) in line 7,8,17 and (Missing ';' at '{') in line 8.

Thanks,
Suresh
NitishNitish
Hi Suresh,

Instead of this
accIds.add(cl.accountId){
}
just put remove curly braces
accIds.add(cl.accountId);
on line 8.
and for other errors related to accountId check your Classification__c object field. There you will see what's the api name of account lookup on your object and on that basis fetch the id.

Thanks,
Nitish
Sure91Sure91
Hi Nilesh,

Still I am getting error(Missing ';' at '}') on line 9

Here is my code:

Trigger ClassificationTrigger on Classification__c(before insert){

    Set<Id> accIds=new Set<Id>();
    if(Trigger.isInsert && Trigger.isAfter){

        for(Classification__c cl:Trigger.new){
            if(cl.Account_Name__c!=null){
                accIds.add(cl.Account_Name__c)
                    }
        }

        Map<Id,Account> accMap=new Map<Id,Account>([SELECT Id,Industry From Account WHERE Id in : accIds]);

        for(Classification__c clNew:Trigger.new){
            if(accMap.get(clNew.Account_Name__c).External_system__c=='123'){
                clNew.Business_Status__c='Active';
              
            }
        }
        
    }
}
NitishNitish
Hi Suresh,

Just replace  accIds.add(cl.Account_Name__c) with accIds.add(cl.Account_Name__c); on line 8.
Sure91Sure91
Hi Nitish,

Again Error :( 

duplicate value found: <unknown> duplicates value on record with id: <unknown>
Deepali KulshresthaDeepali Kulshrestha
Hi Suresh,

Have you tried my code and make a custom lookup field "Account__c" on  Object "Classification" as I can see in my org my trigger is working perfectly.

Thanks,
Deepali Kulshrestha
Sure91Sure91
Hi Deepali,

Thanks for your help!

I have tried your code as well, not working for me.
Method does not exist or incorrect signature: void put(Id, String) from the type Map<Id,Decimal>(Line 13)
Variable does not exist: Account__r(Line 17)
Below is your code :

trigger Trigg on Classification__c (Before  insert) {
    //It will hold the id's of account associated with  "Classification__c".
    Set<Id> ids=new Set<Id>();
    for(Classification__c cla:Trigger.new){
        if(cla.Account_Name__c !=null){
            ids.add(cla.Account_Name__c);  
        }
    }
    Map<Id,Decimal> mMap=new Map<Id,Decimal>();
    List<Account> accList=new List<Account>();
    accList=[select name,External_system__c from Account where Id in:ids];
    for(Account ac:accList){
        mMap.put(ac.Id,ac.External_system__c);
    }
    for(Classification__c cla:Trigger.new){
        if(mMap.get(cla.Account_Name__c)==123){
            system.debug(':::'+cla.Account__r.External_system__c);
            cla.Business_Status__c='true';
        }
    }
}

Thanks,
Suresh
Deepali KulshresthaDeepali Kulshrestha
Hi,
I have made some changes in the code as per your fields you have created, please try this code:

trigger Trigg on Classification__c (Before  insert) {
    //It will hold the id's of account associated with  "Classification__c".
    Set<Id> ids=new Set<Id>();
    for(Classification__c cla:Trigger.new){
        if(cla.Account_Name__c !=null){
            ids.add(cla.Account_Name__c);  
        }
    }
    Map<Id,String> mMap=new Map<Id,String>();
    List<Account> accList=new List<Account>();
    accList=[select name,External_system__c from Account where Id in:ids];
    for(Account ac:accList){
        mMap.put(ac.Id,ac.External_system__c);
    }
    for(Classification__c cla:Trigger.new){
        if(mMap.get(cla.Account_Name__c)=='123'){
            system.debug(':::'+cla.Account_Name__r.External_system__c);
            cla.Business_Status__c=true;
        }
    }
}
and I have used "Business_Status__c" field type is boolean.
If it helps ,Please make it Best Answer.

Thanks.
Sure91Sure91
Hi Deepali,

As I am new to coding, can you please add comment for each line which will help me to understand it :).

Thanks in Advance.

Regards,
Suresh
Deepali KulshresthaDeepali Kulshrestha
Hi,

//Trigger on clasification__c object to populate its field when inserted.
trigger Trigg on Classification__c (Before  insert) {
    //Set to get the account id's of the "Classification__c" object.
    Set<Id> ids=new Set<Id>();
    for(Classification__c cla:Trigger.new){
        if(cla.Account_Name__c !=null){
            ids.add(cla.Account_Name__c);  
        }
    }
    
    //Map contains the id of account as key and Value as the value in "External_system__c" field. 
    Map<Id,String> mMap=new Map<Id,String>();
    //Retrieving all the account associated with "Classification__c" object .
    List<Account> accList=new List<Account>();
    accList=[select name,External_system__c from Account where Id in:ids];
    
    //Filling the map with values.
    for(Account ac:accList){
        mMap.put(ac.Id,ac.External_system__c);
    }
    
    //Iterating over the values in the Trigger.New
    for(Classification__c cla:Trigger.new){
      //getting the value from map  where key is accountId of "cla" instance of  "Classification__c" object 
   //here "mMap.get(cla.Account_Name__c)" will return value in field "External_system__c" of account associated with "cla" instance of Classification__c object. 
        if(mMap.get(cla.Account_Name__c)=='123'){
           //populating the value to true if field in the account "External_system__c" associated with the instance of clasification__c object. 
           cla.Business_Status__c=true;
        }
    }
}
I hope you find the above solution helpful. Please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
This was selected as the best answer
Sure91Sure91
Thanks a lot Nitish & a big thanks to Deepali for your help and efforts !!! fianlly it worked :) 
Sure91Sure91
Just one last question, Do I need to create test class for this ?
NitishNitish
Hi Suresh,

For best practices we create one trigger per object and a Trigger Helper class. If you are following this process than yes you should write Test class or else if in any other test class you are creating any Classicifcation__c object then it will get the coverage from there.
Remmember to deploy Trigger to Production you need atleast 1% or code coverage.

Thanks,
Nitish
Sure91Sure91
Can I achieve above things by job/workflow/process builder ? Because I have more than 8000 record so I may get governor error.