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
Christopher ShadeChristopher Shade 

Trigger with Criteria

I'm going through the intro to Apex Trigger's and SalesForce has you build the trigger below.

How would I add critera to the Trigger below so that the variable Books doesn't contain all records in the object Book__c? 

For instance, it is apply a discount to the Price__c field.  If I only wanted apply the discount if the price were beneath a given amount how would I code that?

trigger HelloWorldTrigger on Book__c (before insert) {

   Book__c[] books = Trigger.new;

   MyHelloWorld.applyDiscount(books);
}

Thanks.
bob_buzzardbob_buzzard
The trigger won't contain all records for the Book__c object, just up to 200 that have been inserted as part of the current transaction.

To exclude some of the records from the Trigger.new list, you'd simply create a new list, iterate the trigger records and only add those beneath the threshold, e.g.

trigger HelloWorldTrigger on Book__c (before insert) 
{
   Book__c[] books = Trigger.new;
   List<Book__c> booksForDiscount=new List<Book__c>();
   for (Book__c book : books)
   {
       if (book.Price__c < 20)
       {
           booksForDiscount.add(book);
       }
   }
   MyHelloWorld.applyDiscount(booksForDiscount);
}