You need to sign in to do that
Don't have an account?
Akshay Shrivastava
I want to show number of child object records in parent object field. soo i writed this code ..can any one tell me the code is right or not and also how to execute in anonymous window
public class Processor
{
@future
public static void count(Set<id> setId)
{
List<parent__c> lst = [select id,noOfrecords__c , (select id from childs__r) from parent__c where id in :setId ];
for( parent__c acc : lst )
{
List<child__c> lstCount = acc.childs__r ;
acc.noOfrecords__c = lstCount.size();
}
update lst;
}
}
{
@future
public static void count(Set<id> setId)
{
List<parent__c> lst = [select id,noOfrecords__c , (select id from childs__r) from parent__c where id in :setId ];
for( parent__c acc : lst )
{
List<child__c> lstCount = acc.childs__r ;
acc.noOfrecords__c = lstCount.size();
}
update lst;
}
}
Try The Below Code Please Mark It As Best Answer If it Helps
Thank You!
All Answers
Try The Below Code Please Mark It As Best Answer If it Helps
Thank You!
in place of AccountID we have to write our lookup relation field name
trigger triggerName on child__c (After Insert,After Update,After Delete) {
List<parent__c> accList=new List<parent__c>();
Set<Id> setAccIds = new Set<Id>();
if(Trigger.isInsert){
if(trigger.isAfter){
for(child__c con : Trigger.new){
if(con.task1__c != null){ // task1__c is field name of lookup relationship
setAccIds.add(con.task1__c);
}
}
}
}
system.debug('setAccIds ==> '+setAccIds);
if(Trigger.isUpdate){
if(trigger.isAfter){
for(child__c con : Trigger.new){
if(con.task1__c!=Trigger.oldMap.get(con.Id).task1__c){
setAccIds.add(con.task1__c);
setAccIds.add(Trigger.oldMap.get(con.Id).task1__c);
}
}
}
}
if(Trigger.isDelete){
if(trigger.isAfter){
for(child__c con : Trigger.old) {
if(con.task1__c != null){
setAccIds.add(con.task1__c);
}
}
}
}
for(parent__c acc :[select id,noOfrecords__c , (Select id,name from childs__r) from parent__c where Id in : setAccIds]){
acc.noOfrecords__c = acc.childs__r.size();
acclist.add(acc);
}
if(acclist.size()>0){
update accList;
}
}
Please Mark It As Best Answer If it Helps So It Can Help Others In Future.And It Motivates us To Give More In Community
Thank You!