19 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 ...
  • 22.1k
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 ...
  • 50.4k
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 ...
  • 144k
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(...
  • 144k
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 ...
  • 444k
11 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 ...
  • 4,593
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 ...
  • 444k
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<...
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 ...
  • 144k
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) ...
  • 28.6k
7 votes
Accepted

Create a trigger to get current IP address

I have used the below code to get the IP address of the logged/current user. Hope this helps. Thanks Map<String, String> headersMap = ApexPages.currentPage().getHeaders(); // True-...
  • 2,797
7 votes
Accepted

Access user creating a record in before insert trigger

A call to System.UserInfo.getUserId() will give you the ID of the currently executing user during any transaction. This should solve your problem because the CreatedById always receives this value ...
7 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 ...
  • 24.8k
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 ...
  • 144k
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 ...
  • 444k
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.
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 ...
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 ...
  • 50.4k
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 ...
  • 5,195
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 ...
  • 144k
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, ...
  • 144k
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. ...
  • 53.3k
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, ...
  • 50.4k
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 ...
  • 63.6k
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 ...
  • 1,090
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(...
  • 88.1k
6 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 ...
  • 50.4k
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 ...
  • 131k
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; ...
  • 28.6k
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 ...

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