Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Questions tagged [trigger]

A trigger is a feature of the Salesforce platform consisting of Apex code that executes before or after DML operations.

96
votes
10answers
29k views

How do I start to debug my own Apex code?

Sometimes questions are posted here that would best be answered by helping the questioner learn how to do their own debugging. (Remember that proverb?) I'd like to have something to link to on this ...
80
votes
8answers
19k views

Can we determine if the Salesforce instance is production org or a Sandbox org?

I am looking for the most efficient way of identifying the type of org (Production or Sandbox) via Apex code. URL scraping is not useful to me, since I'd like to get this information inside a trigger ...
46
votes
2answers
15k views

Lead Conversion Trigger Order of Execution

I've got a project where I'm looking to tweak the standard lead conversion process. Triggers and lead conversion has always been funky in past projects so I was hoping to start the design off by ...
43
votes
3answers
11k views

General trigger bulkification - best practices

A general question asked from time to time on stack exchange is question of trigger bulkification. Therefore I have 2 questions: Which best practices are you using? What is the best way to handle ...
42
votes
5answers
2k views

What are all of the reasons why Salesforce customers should upgrade the API version on their Apex classes, triggers, and pages?

I haven't been able to find any official documentation or community discussion of the compelling reasons to upgrade the API version on Apex classes, triggers, and pages. I know there is the general ...
42
votes
4answers
13k views

Workflow rule causing trigger to fire twice

I need to be able to detect that the trigger execution is happening because of a workflow field update. There is a suggestion in the cookbook: Controlling Recursive Triggers But this solution is not ...
37
votes
4answers
25k views

Deleting Triggers/Classes from Production

I was recently told ( Deleting a Class with IDE - cannot delete from Production? ): You cannot delete a class in production directly. You will need delete the class from your sandbox and then ...
36
votes
4answers
20k views

How do I generate a random string?

How does one generate a random string sequence with Apex? I need to generate a code when a particular object is created in our Salesforce environment. I'd like the code to contain numbers from 0-9 ...
35
votes
1answer
13k views

Infering sObject Type from Id or collection of Id's

If I have an instance of an Id variable that has been populated with a value, is there way to infer the sObject type of that Id using a describe call. So if I did: Set<id> parentIds = new ...
31
votes
5answers
18k views

How to generate a GUID/UUID?

What is the best way to generate a GUID/UUID from Apex code (such as a trigger)? Preferably in the following format: nnnnnnnn-nnnn-nnnn-nnnnnnnnnnnnnnnnn Example: 13219ec0-3a81-44c5-a300-...
31
votes
1answer
5k views

Generic Apex Trigger

So I was kind of throwing round the idea of making a generic apex trigger that is callable by multiple objects. Say you have the following sObjects: Account Sales__c Sales_Contacts__c And I wanted ...
28
votes
2answers
28k views

HTTP Callout from Triggers

I have a trigger on the Custom Object that calls a class. That class makes an HTTP GET request to a Web Service. However I get the following error: Callout from triggers are currently not supported. ...
24
votes
3answers
9k views

Generically Walk sObject Fields

I've become quite comfortable with writing bulkified triggers that compare before and after values of specific fields. I've bumped into two cases where I'd like to do this generically for all fields. ...
23
votes
2answers
8k views

How can I determine how many future calls have been executed in 24 hours?

I just ran into a huge gotcha in Salesforce: the 24 hr limit on # of future calls - cf. http://www.sundoginteractive.com/index.php?/sunblog/posts/governor-limit-gotchas-part-1-the-future-call/. I ...
22
votes
5answers
14k views

How can we disable triggers, Validation Rules and workflow rules in salesforce org. [on off - switch]

How can we disable triggers, Validation Rules and workflow rules in salesforce org. This becomes really needed and important when we are doing data migration(data imports) in salesforce. The way I ...
19
votes
1answer
7k views

Check that criteria are met in a before insert trigger

I want to check whether a certain criteria is met or not using a trigger before inserting a record. if it meets the criteria, i insert the record, but if it does not i want to display an error message ...
19
votes
1answer
13k views

Do changes to rollup summary fields cause triggers to fire?

If a parent record has a roll up summary field, let's say to calculate the number of line items on an opportunity, if a new line item is added (and hence the value of the rollup field is changed), ...
18
votes
1answer
39k views

Just update when a specific field changes

I created a trigger to open a case in my account if (Atribuido__c == 'SIM') I want the trigger to fire just when this field is updated. If this field is already updated and I update any other fields ...
18
votes
6answers
4k views

Can I store information even if the trigger throws an exception?

I currently have a trigger which sometimes fails when new information is inserted from a 3rd party system. I can't simply check the logs as it usually happens during the night and it's not easy to ...
17
votes
6answers
30k views

How to write a unit-test / test class for trigger?

How do I write a unit-test / test class for a trigger? What are my options? Inline with the trigger? New Class?
16
votes
5answers
6k views

What sObject properties don't cause triggers to fire?

I recently discovered that updating your Chatter profile image won't cause the User trigger to fire (for fields SmallPhotoUrl or FullPhotoUrl). I was wondering what other fields, when updated, won't ...
16
votes
2answers
4k views

Are triggers able to modify records locked by an approval process?

A lookup field in a custom object needs to be updated after the record is submitted for approval and locked. Is the trigger able to achieve this, even if the record is locked?
16
votes
2answers
8k views

Trigger .isExecuting Clarification

So I have been wanting some clear cut answers on this for a while and most of the documentation that I can find is fairly vague. Mike Leach has an excellent post explaining the best practices in ...
16
votes
2answers
1k views

Dealing with auto-batching of triggers

I've recently been trying to come to terms with the oddities of the auto-"batching" of triggers. What I'm referring to is how when dealing with more than 200 records in a trigger execution, ...
16
votes
2answers
790 views

Can triggers tell if a Workflow invoked them?

Is there anything available to us in Apex that can be used to determine if a trigger was fired by Workflow/Process Builder?
16
votes
3answers
10k views

System.QueryException: Aggregate query does not support queryMore()

I am trying to deploy around 80 Components which include Apex Class,Trigger and Visualforce Pages. But it is failing due to below exception, MyTrigger: execution of BeforeInsert caused by: System....
15
votes
4answers
5k views

System.Exception: Too many SOQL queries: 101 [duplicate]

I am getting a Too many SOQL queries: 101 error on a trigger when I am trying to deploy another trigger. I am posting the trigger which is causing the error. trigger rollupAccountShowings on Account ...
15
votes
1answer
9k views

Simple-to-use “if field exists” logic?

Is there simple to use logic that equals "if a field exists, then...": if( **fieldname__c exists** ) then { ... } ..? I really don't want to have to worry about a ton of class or other logic. I'm ...
15
votes
3answers
4k views

Does upsert fire an Update or Insert trigger? Or both?

When I do an upsert DML which trigger code will handle it? Insert Update Both ? Is there a pattern to solve potential duplicate executions if it is 3)?
15
votes
2answers
4k views

are Triggers (and their delegated classes) or Batch affected by sharing?

I understand with sharing classes run in User Mode, meaning they respect permissions, field-level security and sharing rules of the current user. I understand without sharing classes run in System ...
15
votes
2answers
732 views

Opportunity Management

This is my first post here on the StackExchange and hoping someone can help. I have been tasked with finding a way to prevent users from moving to 70% or greater probability in an opportunity when ...
14
votes
3answers
49k views

System.FinalException: Record is read-only: Trigger.updateCompetitors: line 24

I am writing a trigger to get all the Opportunity competitors into a field on Opportunity, however, getting an error while testing it. Error: updateCompetitors: execution of AfterUpdate caused by: ...
14
votes
3answers
9k views

How to avoid recursive trigger other than the classic 'class w/ static variable' pattern?

How can we avoid trigger get executed again and again (recursive trigger)? One way is to have a class with static variable and have boolean value and check it is true or false and changing the boolean ...
14
votes
2answers
3k views

Delete triggers don't cascade master to detail, so why not hand-cascade on the master?

I understand from experience that Master-Detail deletion triggers do not cascade. For example if I delete my Account the Contact deletion triggers don't fire. Having devoured the first and second ...
14
votes
1answer
15k views

Exeception on After Insert, Record is read only

I'm writing a trigger for new opportunity products to populate a field Product_Category__c (on opportunity lineitem) getting the value from Product_Category_new__c (on Product). This is my trigger: ...
14
votes
2answers
6k views

I need my method to return two Maps. Is this possible?

How would I go about returning two Maps from a method? If it is not possible, could you offer a work-around? I would like my Method to return: Map(Lead, Set<Date>) Map(Lead, Set<String>)
14
votes
1answer
14k views

How to Convert 18 char Id to 15 char Id using substring in Apex trigger

I have a trigger where i am assigning ID to a cusotm field like below - D.customfield__c = acc.Id; The ID is coming as 00P28000000EwpjEA0 But i need only 00P28000000Ewpj 15 char. Is there is a way ...
14
votes
4answers
14k views

Deleting records in an after trigger

I have this trigger on a custom object trigger mytrigger on Merchandise__c (after insert) { merchandise__c m = [select name from merchandise__c where id =:trigger.new[0].id]; m.name = 'hi'; delete m; ...
14
votes
2answers
4k views

How do you write a unit test for a trigger whose only function is to make a callout?

What is considered a best practice for writing a unit test (to maintain code coverage) on a trigger whose sole function is making a callout (Which also means it has to use a future method)? Neither ...
14
votes
3answers
13k views

Trigger on Case EmailMessage

I have a customer that wants to have a field on the case updated when a user sends an email from a case. For simplicity sake, let's just say we need to put some string into a custom field each time ...
14
votes
1answer
755 views

Consolidate trigger methods or not?

I have a general best practices question about triggers. I have created a handful of triggers that perform different actions but are called by the same event, such as after account update/insert/...
14
votes
3answers
1k views

Batch Apex in AppExchange package and orgs with related triggers that call @Future methods

Here's the problem: when an org has a trigger that calls an @Future method, any batch Apex that fires that trigger will fail, since you cannot call an @Future method from an @Future method OR from ...
14
votes
1answer
496 views

Documentation Incorrect? Is it possible to cover/deploy triggers on Platform Events?

I am about to roll out some code which uses Platform Events, and hitting a troublesome roadblock in testing. Is calling Test.stopTest() supposed to cause subscriber triggers to fire and subsequently ...
13
votes
1answer
15k views

What are recursive triggers? how to control them? Please provide an example also

What are recursive triggers? How can we control them, or prevent infinite recursion? Are these any risks inherent in them, and any limits that we should be aware of? Please explain with an example.
13
votes
3answers
7k views

Trigger Old Context Variables (oldMap, old)

According to the documentation, Trigger.old and Trigger.oldMap are only available in update and delete Triggers. Are these variables null otherwise, or are they just empty? Would Trigger.old.isEmpty(...
13
votes
4answers
17k views

How should I determine whether to use Before or After when writing a trigger?

The title pretty much says it all.
13
votes
5answers
12k views

Do Apex Triggers have access to formula fields?

On the Contact object I have a custom formula field call Prioirity__c that is defined as: IF(ISPICKVAL(Account.Rating, 'Very Hot'), 'High', '') I also have a trigger defined for the contact object ...
13
votes
2answers
1k views

DML operation and async Queueable job - which executes first?

I have a trigger after insert on some arbitrary entity: trigger OpportunityTrigger on Opportunity (after insert) { // not bulkified for the sake of simplicity ID jobID = System.enqueueJob(...
13
votes
2answers
6k views

what is the best way to delete a set of records during insert?

I have created a trigger that is supposed to avoid a (lead) record being inserted if it contains an email found in another (contact) record. I am able to get the trigger to update (lead) fields if a ...
13
votes
3answers
6k views

Execute an action / run a trigger every time a User logs in to Salesforce

Is there any way to consistently execute a piece of Apex code whenever a User logs in to Salesforce? Posts such as this one seem to suggest that triggers on updates to the User object's 'LastLoginDate'...