You need to sign in to do that
Don't have an account?

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:
But the code doesn't work at all. I've even have nothing display on the debug console.
Please help :(
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 :(
thanks
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: I hope this will work. Please mark as best answer if helped.
Regards,
Ramakant