20 votes
Accepted

Difference between trigger.new and trigger.newmap

Suppose you have a custom object Custom_obj__c Trigger.New means it is a List<Custom_obj__c> and Trigger.NewMap means it is a map<Id, Custom_obj__c> In before insert context your ...
Ratan Paul's user avatar
  • 22.5k
14 votes
Accepted

How to remove records to be processed from before update trigger

Background: understanding collections and references Your understanding isn't quite correct. Collections (lists, sets, and maps) generally store non-primitive types (i.e. pretty much everything that ...
Derek F's user avatar
  • 59.3k
12 votes
Accepted

Is it possible to write Trigger for Before & After DML?

It is quite possible, and in fact recommended (if you need trigger logic on both events). See also: Trigger Frameworks and Apex Trigger Best Practices Triggers (Apex Developer Guide) A common ...
Adrian Larson's user avatar
  • 149k
12 votes
Accepted

Customize error message for trigger and display error message below the field

You can add an error to a specific field using the addError method as follows: SObject someRecord; someRecord.SomeField__c.addError('Custom Message'); //or someRecord.someField__c.addError(...
Adrian Larson's user avatar
  • 149k
12 votes
Accepted

Do apex methods invoke at the same time in a trigger?

Apex Code is single-threaded. This means that your code runs sequentially, from top to bottom, until the end of the method. If you have validation occurring first, followed by other updates, your code ...
sfdcfox's user avatar
  • 481k
12 votes
Accepted

Trigger flow if a specific field on the updated record changed

Flow Builder's before-save trigger executes before the record is saved to the database. For an existing record, the record that's in the database still has the previous field values, while $Record ...
shannonsans's user avatar
  • 4,693
10 votes
Accepted

APEX Lock and Unlock a Record

== is for equality checks, = is for assignment. As such: If (soAccount.ISLock__c = True){ will assign the value of true to IsLock__c, and this statement will always be true. For this reason, I ...
sfdcfox's user avatar
  • 481k
8 votes

Is there any way to use only one SOQL for both before and after trigger on the same object?

This is a good time to learn about the Lazy Load pattern. You can write your cache in such a way that you only consume the query if you actually need the data. Now if you make a reference to this Apex ...
Adrian Larson's user avatar
  • 149k
8 votes
Accepted

Is there any way to use only one SOQL for both before and after trigger on the same object?

Yes static variables are meant for same purpose . Create a static list in your helper class and use same in your before trigger and after trigger public class cachequery { public static List<...
Mohith Shrivastava's user avatar
8 votes

Difference between trigger.new and trigger.newmap

trigger.new is simply a list of the records being processed by the trigger, so if all you need to do is loop through them then you can use that. trigger.newMap just allows you to target specific ...
Matt Lacey's user avatar
  • 25.3k
8 votes

Variable does not exist:Trigger

You have a typo: Trigger.oldMap.get.(cl.id).Initial_Estimate__c should be: Trigger.oldMap.get(cl.id).Initial_Estimate__c You probably also need to apply an explicit cast, like: ((Claim__c) ...
Phil W's user avatar
  • 34.1k
7 votes
Accepted

Do we lose flexibility of Before trigger by shifting to Process Builder?

If you care about order of execution, triggers are far from obsolete, and this consideration still offers a compelling argument for why you would choose an Apex Trigger over Process Builder. If you ...
Adrian Larson's user avatar
  • 149k
7 votes
Accepted

The code block containing 'addError' is being executed but no error thrown during record save

The problem is this line here: objOpp = new Opportunity(id = mapOfOpportunity.get(eachKey)[0].Id); You're adding an error to a record that exists only in memory. Errors will only surface when you ...
sfdcfox's user avatar
  • 481k
7 votes
Accepted

Before Delete Trigger, Need to Delete Linked Record, getting "De-reference Null Object" Error

This is happening because Trigger.new is not available on before delete context. You'll want to use Trigger.old instead. Check this document about Trigger Context Variables.
Renato Oliveira's user avatar
7 votes
Accepted

Invalid loop variable type expected SObject was Relatie__c

Trigger.new is generic List while iterating you have to typecast it into List. So your for loop will be, for(Relatie__c rc :(List<Relatie__c >) Trigger.New){ } That being said, I found few ...
Pranay Jaiswal's user avatar
7 votes
Accepted

Why do we need to update related records in an after trigger but not before?

If I understand your question correctly, then you actually can take your related record update logic and put it in either a before or after trigger. Salesforce's suggestion is that before triggers ...
Derek F's user avatar
  • 59.3k
7 votes

Static Approach in recursive trigger

We need to take measures to prevent recursion precisely because the approach you're suggesting (compare old and new trigger context records) doesn't work. Or, at the very least, it doesn't work in all ...
Derek F's user avatar
  • 59.3k
6 votes
Accepted

Trigger Error in salesforce

I just checked lastmodified by id is null on a before insert event and this makes sense. For example (hastily written trigger based approach, not best practice!): trigger eventTrigger on Event (before ...
Girbot's user avatar
  • 5,405
6 votes
Accepted

Trigger NullPointerException Error Before Update

You can't set cross object fields on trigger context records. When you specify Case__r on a record in your trigger.new collection, it is null. Hence trying to set its Status results in an attempt to ...
Adrian Larson's user avatar
  • 149k
6 votes
Accepted

How to get parent data in a before insert context?

You can just query the PricebookEntry records instead: Set<Id> entryIds = new Set<Id>(); for (QuoteLineItem item : trigger.new) entryIds.add(item.PricebookEntryId); Map<Id, ...
Adrian Larson's user avatar
  • 149k
6 votes

Is this trigger properly bulkified?

Yes and no No need for seperate block for update and insert they are doing almost (thanks DerekF for pointing out the additional if) the same thing and they can be consolidated pretty efficiently. ...
Eric's user avatar
  • 54k
6 votes
Accepted

Why doesn't this trigger work?

It isn't working because the Asset Id field is null in the before insert context. Records do not have Ids until after insert. Beyond that, you're updating an Account record in your Asset trigger, ...
Derek F's user avatar
  • 59.3k
6 votes

Before Trigger & Formula Field Reliability

As an addendum to @adrianLarson comment: Cross-object formula fields may be available in the before trigger context if the parent relationship is based on a required field or on a lookup field with ...
cropredy's user avatar
  • 69.9k
6 votes
Accepted

Custom Validation using Trigger throwing System.FinalException: SObject row does not allow errors

The problem is that you are calling addError on Trigger.OldMap instead of Trigger.NewMap. When declaring the signature for checkForStageDuration you have it (oldMap, newMap) but when you are passing ...
Kyle's user avatar
  • 1,170
6 votes
Accepted

Why is my flag not working on maximum trigger depth exceeded

You're seeing recursion because your recursion guard is in the wrong place. When this gets executed: AankoopDetailTriggerHandler.isBeforeInsert(trigger.new); if(...
David Reed's user avatar
  • 92.1k
6 votes

How do I do a universal SOQL?

You can make use of dynamic SOQL: String type = 'Abc__c'; Map<Id, SObject> m = new Map<Id, SObject>(Database.query('SELECT Id FROM ' + type)); Also see the SObject documentation for ...
Keith C's user avatar
  • 135k
6 votes
Accepted

How do I do a universal SOQL?

It is possible to get the object's type from the ID then use this in the dynamic SOQL. For example: Id id = Id.valueOf(tool.cId__c); String objectAPIName = id.getSobjectType().getDescribe().name; ...
Phil W's user avatar
  • 34.1k
6 votes
Accepted

"Compile Error: Variable does not exist" but I've declared it in the line above

You should put { and } around the code block below the if. As it is now, the if only applies to one line of code, the one directly following it. And so the declaration is not visible to the following ...
Sander de Jong's user avatar
6 votes

CPU limit issue while testing APex trigger

Inserting throngs upon throngs of records for tests is pretty much never the answer. Even if you didn't run into CPU limits, tests are still subject to the other governor limits as well (including the ...
Derek F's user avatar
  • 59.3k
5 votes
Accepted

I am trying to write a trigger which is partially working

You are trying to add the Id of an Order to OrderIds before you insert the orders. sObjects don't have Ids before you insert them* I'd suggest taking your insert OrderToInsert; DML statement outside ...
Derek F's user avatar
  • 59.3k

Only top scored, non community-wiki answers of a minimum length are eligible