0

Not sure if my syntax is correct, what I'm trying to achive is updating a text field (X80_20__c), where the data is coming from a formula text field (X80_20_Yes_or_No__c). The output from the formula field produces a Yes or No value.

This is the Apex trigger I attempted but its not populating the X80_20__c field. Any help would be appreciated or would a Apex Class be better to do in this situation? Also, I'm avoiding in using a workflow trigger or process builder for this.

trigger a8020 on Account (before insert,before update) {
    List obj = [SELECT Id,Name,X80_20_Yes_or_No__c,X80_20__c FROM Account WHERE
 (X80_20_Yes_or_No__c = 'Yes' OR X80_20_Yes_or_no__c = 'No') AND
 Outlet_Type__c = 'Home Depot' AND Has_1_2_3x5_DULO__c = 'Yes' ]; 

    for (Account a: obj) {
        string s = a.X80_20_Yes_or_No__c; 
        a.X80_20__c = s;  
    } 

    update obj; 
}

1 Answer 1

1

Formula fields are not populated in before insert context, so your query is going to return a set of existing Accounts, not the ones being inserted. (This goes double because your query doesn't include any Id IN criterion in the WHERE clause, so it's running across the whole database).

Additionally, in a before insert context, you do not need to perform an update DML to commit changes you make to objects in the trigger.

In this case, since you're iterating over a set that will either be empty or a group of unrelated existing Accounts rather than Trigger.new, the overall outcome is that nothing happens to your newly inserted accounts, and you update some existing records in your database.

If you need to pre-populate this field, you may want to simply implement the formula logic in your trigger. You can iterate over Trigger.new, access the Account fields directly (no SOQL required), and update your field without needing DML.

Lastly, since List (rather than List<Account>) is not a valid type in Apex, I don't believe this will compile as written.

3
  • I'm not trying to insert any new records, but update a field located in the Account object. I tried (after update) and that didn't work either.
    – rouqeOne
    Feb 22, 2018 at 22:50
  • I understand you are not inserting objects. Your trigger fires on insert, when an Account is inserted, which is one among several issues here.
    – David Reed
    Feb 22, 2018 at 23:19
  • FYI you should be able to get the value even before insert if you call recalculateFormulas().
    – Adrian Larson
    Feb 23, 2018 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.