The Stack Overflow podcast is back! Listen to an interview with our new CEO.

Hot answers tagged

7

No, it is not technically possible. Synchronous callouts in Triggers are not allowed. There is an Idea to have Salesforce do this, but it's already a decade old, and may never be implemented. The main concern about callouts during triggers is that it will significantly increase database contention, which may cause deadlocks as the database has to hold record ...


4

I've seen several discussions around this issue but no clear recommendation. Certainly not one that is well suited to ISV development. Post from Chuck Liddell in the Official: Platform Events success group: For a normal Platform Event trigger that moves into the Error State (stops listening) because of errors, you can edit the trigger code, save, and ...


3

FIXED! According to tech support... In winter'20 release, there was additional functionality added for retrying the Platform event trigger without the EventBus.RetryableException implementation. The change - In case of any Limit exceptions while Platform event trigger is executing then the platform trigger context will be retried for 10 times ...


3

This trigger pattern is going to cause nightmares. When you write your unit tests, they will either check very little about what your code does (and provide variable coverage), or they will fail intermittently, depending on when you run them. First of all, you should move your code out of the trigger body and into an Apex Class, which is something you should ...


3

This error indicates that a DML update is being performed on some List<sObject>, and the relevant list contains the same object multiple times. Scanning through updateRelationships(), the proximate cause is this line: update updateCards; which is performing an update on a List<CaptureCard__c>. The better, and more typical, pattern is to ...


2

I don't see anyplace in your code where you're validating that the Dates of all related CompanyOrder__c have StartDates and EndDates that do not overlap with one another. That would require a query for all CompanyOrder__c's related to the parent Opportunity, then iterating through the StartDates and EndDates since not all instances of them will necessarily ...


2

Edited: You have a trigger on Budget_Item__c records. You need to make sure you can handle the scenario where multiple Budget Items are being updated from different budgets. Even if this is unrealistic, you should at least code to support that scenario. Likewise, you shouldn't be doing all your logic in the trigger and certainly don't always want to be ...


2

You need to set the Budget__c field value before inserting the Campaign. I think this can also be simplified to: List<Campaign> ca = new List <Campaign>(); for(Budget_Item__c bi : [SELECT Id, <etc...> FROM Budget_Item__c WHERE Id IN: Trigger.newMap.keySet()]){ if(bi.Create_Campaign__c == true){ Campaign c = new Campaign(); ...


2

You will need to implement this validation on the front end, using a Visualforce page or Lightning component. Your custom UI - perhaps an override of the Edit action - can make a callout to validate data input prior to initiating DML at all. You then have full freedom to interact with the user's active browser session based upon the response from your web ...


2

Your problem is here: timeCardIntegration.add( new Timecard_integration__c ( Name = tc.Id, hours__c= decimal.valueOf(hoursEntered.get(j)), CurrencyIsoCode= tc.CurrencyIsoCode )); hoursEntered.get(j) is a record, but Decimal.valueOf can only work on certain data types, such as a String or an Integer. You need to specify which value you're ...


2

This example highlights a common programming anti-pattern. The only reason you are having difficulty here is that you have conflated your filter and your action. You should instead have two methods here: one which filters only records whose name has changed, and one which manipulates all records on which you should act. Basically: public with sharing class ...


2

The error should be in the line sendTo.add(opp.Name); List<String> sendTo = new List<String>(); sendTo.add(opp.Name); mail.setToAddresses(sendTo); You are setting the opportunity name as an email address and it could not be. A valid email information is necessary. You should get the contact email or user email, for example.


2

The insert of the WorkOrder fails because the system cannot access the related Opportunity__c record. Looking at the code in the test class I noticed something which is considered bad practice: The Id for the record is hardcoded. WorkOrder workO1 = new WorkOrder (Rates__c='Testing Metrics Only 1',Plan_Price__c=1,Status='Completed',Omit_from_Stats__c=True,...


2

You passed the maps into your handler code so you really just need to compare them by using the acc ID as the key between the two maps for (Account acc_i : accMap.values()) { if(acc_i.IsActive__c==true && acc_i.IsActive__c != accoldMap.get(acc_i.Id).IsActive__c){ System.debug('You can update'); acc_i....


2

You're running a before insert trigger, but your trigger's action depends on querying the database for existing Cases - Cases that aren't part of the current trigger invocation but have already been committed to the database. In addition to sfdcfox's and Adrian's comments, you'll need to insert test data in two DML statements: the first (with 10, or 25, or ...


2

The main flag that can tell you a retry has happened, is that a new ID you stashed in a static variable is no longer valid. If your trigger code creates any new records you could check those IDs against the DB. I wish Salesforce gave us a better way to do this. One crafty way I thought of in another thread was to enqueue a disposable Queueable class, for no ...


1

It appears you forgot to add the records to the list: for(integer i=0; i<10; i++){ Case ca = new Case(); ca.Subject = 'Test Subject - Field Test ' + i; ca.Description = 'Test Description - Field Test ' + i; ca.Origin = 'Web Email'; ca.Type = 'Other'; ca.Reason = 'Other'; // These should be set by the trigger! //ca....


1

If you want your trigger to fire only when IsActive__c is changed to true, then you will have to check for two conditions. Old value of IsActive__c is not same as new value of IsActive__c New value of IsActive__c is true So that is how your condition should be, so replace below code if(acc_i.IsActive__c==true) with if(acc.IsActive__c != accoldMap.get(...


1

added based on comments As you need to create records in custom object based on Account record changes, lets consider custom object AccountHistory__c with corresponding fields Account__c, NewName__c, OldName__c and other such fields. As you need to create different object, you should use after trigger. Below will be sample trigger: trigger AccountTrigger ...


1

Yes, you can certainly do so. The usual point of splitting out logic in to different methods is legibility. Many "trigger frameworks" actually do have a single method, that then branches depending on the trigger context. Here's one such example: trigger X on Y (before insert, before update, before delete, after insert, after update, after delete, after ...


1

The system fields are not populated in the before insert context hence s.createddate will be null and performing an operation on null object would result into Attempt to de-reference a null object exception. You can instead use System.Now() or DateTime.Now() instead of createddate. So your trigger code could be trigger Assignedrollno on student__c (...


1

added According to Order of Execution, after triggers are executed AFTER ves the record to the database, but doesn't commit yet. So, it is not logical to manipulate the record which has been sent to database already. You need to make changes in the record BEFORE sending the record to database i.e., before update If you are changing the trigger context ...


1

This is a case where you will need to modify the code under test to test it. You will need a class if your trigger logic isn't already in a class: public class Triggers { @TestVisible private static DateTime nowOverride; public static DateTime now() { return nowOverride == null ? System.now() : nowOverride; } } then your trigger ...


1

Your problem is the &&. You need to use the word AND instead. Similarly, you would use OR for an either-or filter.


1

I'd like to offer an improved version of the original answer by @Maria Illarionova by removing the nested loops and fixing one potential error public static void processAccounts(Map<Id, Account> accounts) { List<Contact> contactsToCheck = [ SELECT Id, Type__c, AccountId FROM Contact WHERE (Type__c = 'New' ...


1

trigger setOpportunityOwner on Task (before insert, before update) { MAP<Id, Task> taskmap = [Select Owner.UserName FROM Opportunity WHERE Id IN :Trigger.new]; for(Task o: Trigger.new) { o.Opp_Owner__c = taskmap.get(o.id).owner.UserName; } } The first issue with your code is that you're taking an Opportunity query and assigning it ...


1

from your description and the code you posted I think you want to achieve that if a task is getting inserted or updated, the activity date should be written on all related contacts. This would be my approach public static void updateContact(List<Task> tks) { Map<Id, Contact> affectedContacts = new Map<Id, Contact>([SELECT Id, ...


1

You need to add the End_Date__c to the query on parentsRep Map. parentReps = new Map<Id, Rep__c>([SELECT Id, Rep_Type__c, (SELECT Id, Type__c, End_Date__c FROM Role_Histories__r WHERE End_Date__c = null ORDER BY CreatedDate DESC LIMIT 1) FROM Rep__c WHERE Id IN :listIds]); RoleHistoryAfterTrigger: execution of BeforeUpdate caused by: System....


1

@Rodrigo is correct. After you clarified your Question in the comments below. I will make some assumptions that you should have made in your question. 1.There is a field on the Role_History__c object called RepresentativeId__c which is a lookup field to the representative. 2. When a new Role_History__c records is inserted, the RepresentativeId__c field ...


1

Taking a step back...You shouldn't be doing any real logic in the trigger. Imagine if you have to add functionality to this object and you risk breaking everything in that object because you put everything in the trigger. The trigger should pass the objects to separate methods of a different class depending on the situation (update, insert, etc). This means ...


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