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
Edgar KAMDEMEdgar KAMDEM 

Salesforce Questions Tags Users Badges Unanswered Ask Question Creating a trigger that insert and delete a value on a field with a junction relationship object

I work with 3 objects : Book, Loan, Contact. Book and Loan are customs.

Book has a field Title, Contact has a field "Number of Loan". Loan is a junction object (Many to Many) from Book and Contact.

The idea is that, whenever a there a Loan is inserted, the value in number_of_loan (of the related contact) get incremented and when we delete it get decremented.

To perform that I decided to create a trigger on the Object Loan.

Here it is: 
trigger BorrowedBooksTrigger on Loan__c (after insert, after delete) {
    
        Contact c = new Contact();
        Set<Id> lretIdsToQuery = new Set<Id>{};
    
        if (Trigger.isInsert) {
            
            for(Pret__c l: Trigger.new){
              lretIdsToQuery.add(p.Id);
             }
    
             
            List<Contact> relatedContacts = [SELECT Id, Name, Number_of_loan FROM Contact
            WHERE Id IN :lretIdsToQuery];
             
            for(Contact c : relatedContacts) {      
                 system.debug('Number_of_loan added '+ c.Number_of_loan);
                 c.Number_of_loan = c.Number_of_loan+1;
                 update c;
            }  
            
             
        }else if (Trigger.isDelete) {
            
             for(Pret__c l: Trigger.old){
              lretIdsToQuery.add(p.Id);
             }
    
             
            List<Contact> relatedContacts = [SELECT Id, Name, Number_of_loan FROM Contact
            WHERE Id IN :lretIdsToQuery];
             
            for(Contact c : relatedContacts) {      
                 system.debug('Number_of_loan deleted '+ c.Number_of_loan);
                 c.Number_of_loan = c.Number_of_loan-1;
                 update c;
            } 
            
        }
    }

But the code doesn't work at all. I've even have nothing display on the debug console.

Please help :(
sfdcMonkey.comsfdcMonkey.com
hi try below code :
trigger BorrowedBooksTrigger on Loan__c (after insert, after delete) {
    
        Contact c = new Contact();
        Set<Id> lretIdsToQuery = new Set<Id>{};
		List<Contact> lstConUpdate = new List<contact>();
    
        if (Trigger.isInsert) {
            
            for(Loan__c l: Trigger.new){			
              lretIdsToQuery.add(l.ContactId);
             }
    
             
            List<Contact> relatedContacts = [SELECT Id, Name, Number_of_loan FROM Contact
            WHERE Id IN :lretIdsToQuery];
             
            for(Contact c : relatedContacts) {      
                 system.debug('Number_of_loan added '+ c.Number_of_loan);
                 c.Number_of_loan = c.Number_of_loan+1;
				 lstConUpdate.add(c);
                 
            }  
            
             
        }else if (Trigger.isDelete) {
            
             for(Loan__c l: Trigger.old){
              lretIdsToQuery.add(l.ContactId);
             }
    
             
            List<Contact> relatedContacts = [SELECT Id, Name, Number_of_loan FROM Contact
            WHERE Id IN :lretIdsToQuery];
             
            for(Contact c : relatedContacts) {      
                 system.debug('Number_of_loan deleted '+ c.Number_of_loan);
                 c.Number_of_loan = c.Number_of_loan - 1;
                lstConUpdate.add(c);
            } 
            
        }
		
		if(lstConUpdate.size() > 0){
		  update lstConUpdate;
		}
    }
let us know if you have any issue with it or mark it best if it will helps you
thanks

 
RKSalesforceRKSalesforce
Hi Edgar,

You are trying to achieve rollup summary functionality on MasterDetail Relationship. You can simply achieve this by creating Rollup Summary field on Contact object. 
If we talk about your trigger, Your trigger should work in case of update and undelete as well because anyone can edit contact associated to your Loan__c and Deleted Loan may get undeleted at any point of time.
Please use Below code for your reference:
Trigger ContactRecordCount on Contact(After Insert, After Update, After Delete, After UnDelete){
    
    List<ID> contactIds = New List<ID>();
	List<ID> LoanIds = New List<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
        For(Loan__c con: Trigger.New){
            if(con.Contact__c  != null){
                contactIds.add(con.AccountId);
				LoanIds.add(con.Contact__c.Id);
            }  
        }
    }
    If(Trigger.IsDelete){
        For(Loan__c con: Trigger.Old){
            contactIds.add(con.AccountId);
			LoanIds.add(con.Contact__c.Id);
        }
    }
     
    List<Contact> contactListToUPdate = New List<Contact>();
    For(Contact con: [Select Id, Name, Number_of_loan__c, (Select ID, Contact__c FROM Loans__r) FROM Contact WHERE ID = :contactIds]){
		for(Loan__c lon :con.Loans__r){
			con.Number_of_loan__c = con.Loans__r.size();
		}
		contactListToUPdate.add(con);
    }
     
     
    try{
        Update contactListToUPdate;
    }
     Catch(Exception E){
        System.Debug('Error Message: ' + e.getMessage());
    }
}
I hope this will work. Please mark as best answer if helped.

Regards,
Ramakant