• Edgar KAMDEM
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 0
    Replies
I created a trigger that work very except that I got this error when I try to use addError.
Here is my trigger: 
trigger MyTestTrigger on Pret__c (before insert) {
   
       Set<Id> livreNew = new Set<Id>{};
       Set<Id> contactNew = new Set<Id>{};
        for(Pret__c p: Trigger.new){
          
              livreNew.add(p.Livre__c);
              contactNew.add(p.Contact__c);
        }

       
        List<Pret__c> relatedPrets = [SELECT Id, Contact__c, Livre__c FROM Pret__c
        WHERE Livre__c IN :livreNew AND Contact__c IN :contactNew];
        system.debug('relatedPrets '+relatedPrets);
        
            if(!relatedPrets.isEmpty()){
               for(Pret__c p: relatedPrets){
                system.debug('Trigger p.Id '+p.Id);
                Trigger.oldMap.get(p.Id).addError('Error - dupe item');
                }
            }
}
Pret__c is a junction object between Livre__c and Contact__c
Where I'm wrong ? please help :(
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 :(