When to use trigger.new[0] and trigger.new in salesforce?

360    Asked by EllaClarkson in Salesforce , Asked on May 12, 2023
 I understand that trigger.new contains the list of my records with new values of the records. My questions are:
If multiple users work on the same single object and they do an update should I use Trigger.new or trigger.new[0]?
  1. If multiple users work on different records of the same object(say lead) and they do an update should I use Trigger.new or trigger.new[0]?

As an example when a Lead is being converted, I need to check that a contact with the same email does not exist (I know I can do it in duplication rules, but I am doing it in trigger). Now what I did was:

if(!trigger.new[0].status.equalsIgnoreCase('Qualified')) { List existingContacts = [ SELECT Email FROM Contact WHERE Email =: trigger.new[0].Email LIMIT 1 ]; if(!existingContacts.isEmpty()) { trigger.new[0].addError('A contact already exists'); } }

Is it ok to use trigger.new[0] in the above case, as one/more users will convert only one lead at time?
  1. When is ok to use trigger.new[0] and not ok to use trigger.new[0]? I know if you are working on mass records like mass update or mass delete etc., obviously we have to use trigger.new and not trigger.new[0]. But any other scenarios?

Answered by Dipesh Bhardwaj

Each user will have their own and separate transaction , even though they update the same record at the same time. Transaction in Apex We use Trigger.New in salesforce for bulkification and to avoid governor limits during

  • If the request is coming for a single record , then trigger.New[0] mayn't throw an error and still work.
  • However if there is an operation on a bulk of records trigger.New[0] will represent only the first record in the bulk of records.
  • Combining both, it's better and safer to use trigger.new which will support a single record as well as bulk records.



Your Answer

Interviews

Parent Categories