0

I have two custom objects: Loan__c and Book__c. Loan__c has a lookup relationship to the Book__c. I want a trigger to update a number field (minus 1 from the current value) on Book__c object whenever a loan record is created.

Trigger:

trigger LoanTrigger on Loan__c (after insert) {
        
    if(Trigger.isAfter){
      LoanTriggerHandler.updateNumberFields(Trigger.New);
    }
}

Handler class:

public class LoanTriggerHandler { 

    public static void updateNumberFields(List<Loan__c> myLoan) {
        
        Set<Id> bookIds = new Set<Id>();
        
        for (Loan__c loan : myLoan) {
            bookIds.add(loan.Book__c);
        }
        
        List<Book__c> myBook = new List<Book__c>();
        
        For (Loan__c loan: [SELECT Id, Loaned_Out__c FROM Book__c WHERE Id IN :bookIds]) 
        { 
            loan.Loaned_Out__c = loan.Loaned_Out__c - 1; 
            myBook.add (loan); 
        } 
         update myBook;
    }
}

When I try to save the class, it gives me the following error:

Variable does not exist: Loaned_Out__c Method does not exist or
incorrect signature: void add(Loan__c) from the type List<Book__c>
1
  • a Loan__c is not a Book__c, so you can't add a Loan to a List<Book__c>
    – Derek F
    Jul 13 at 16:42
0

You have an compilation error at line :

For (Loan__c loan: [SELECT Id, Loaned_Out__c FROM Book__c WHERE Id IN :bookIds]) 

Here you are querying Book__c but you are expecting Loan__c to be returned. It should be .

For (Book__c book: [SELECT Id, Loaned_Out__c FROM Book__c WHERE Id IN :bookIds]) 

Also this line loan.Loaned_Out__c = loan.Loaned_Out__c - 1; is incorrect as you dont have any reference of loan here.

So if you want your Loaned_Out__c field to be reduced by 1, then you can use this.

public static void updateNumberFields(List<Loan__c> myLoan) {

    Set<Id> bookIds = new Set<Id>();
    for (Loan__c loan : myLoan) {
        bookIds.add(loan.Book__c);
    }
    bookIds.remove(null);

    List<Book__c> myBook = new List<Book__c>();

    for (Book__c book: [SELECT Id Loaned_Out__c FROM Book__c WHERE Id IN :bookIds  AND Loaned_Out__c > 0]) {
        --book.Loaned_Out__c;
        myBook.add(book);
    }
    Database.update(myBook);
}
2
  • Thanks for this. Should I replace loan with book, like book.Loaned_Out__c = book.Loaned_Out__c - 1?? I want o subtract 1 from the current value of loan_out__c field
    – Hari Ha
    Jul 13 at 16:55
  • Updated my answer, Not sure about your real business need, but if you just want to reduce it with 1, then you can just add one more where clause to only get those books where Loaned_Out__c > 0, and then do a Loaned_Out__c - 1. Jul 13 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.