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
Andrew Henderson 6Andrew Henderson 6 

Search child records from Parent in Formula field

I am looking for a means to have a text value result base on searching for the existance of any related records in another object that is the child in the lookup relationship.   That is not a Master-Detail Relationship, but a basic Lookup.  
Mahesh DMahesh D
Hi Andrew,

I feel we can achieve this using the Apex Trigger to populate the child records information into the parent record.

Please find the below example:
 
trigger PrimaryContactCount on Contact (after insert, after delete, after undelete,after update) {
    set<Id> accIds = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Contact con: Trigger.new){
			if(Trigger.isInsert || Trigger.isUndelete || (con.Primary_Contact_del__c != Trigger.oldMap.get(con.Id).Primary_Contact_del__c))
				accIds.add(con.AccountId);            
        }
    }
    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Contact con: Trigger.old){
            if(Trigger.isDelete || (con.Primary_Contact_del__c != Trigger.oldMap.get(con.Id).Primary_Contact_del__c))
				accIds.add(con.AccountId);
        }
    }    
    
    List<Account> accList = [select id, Number_of_Primary_Contacts__c, (Select Id, Primary_Contact_del__c from Contacts) from Account Where ID IN: accIds];
    
    for(Account acc : accList){
        system.debug('Contacts--->'+acc.contacts.size());
        acc.Number_of_Primary_Contacts__c = 0;
        for(Contact con : acc.Contacts) {
			if(con.Primary_Contact_del__c)
				acc.Number_of_Primary_Contacts__c++;
        }
    }
    update accList;
}

You can change this code according to your needs.

Please do let me know if it helps you.

Regards,
Mahesh