0

pretty simple question that I just can't figure. The first snippet updates a record just fine, but the second snippet does nothing, even though it compiles just fine. Many thanks.

Why does this work:

for(Pet__c P : PetList]){

    if(P.Type__c == 'Cat'){
       P.Age__c = 4;}

But this does not?

for(Pet__c P :[SELECT ID,
               Type__c,
               Age__c, 
               FROM Pet__c
               WHERE ID IN :PetList]){

        if(P.Type__c == 'Cat'){
            P.Age__c = 4;}
3
  • Is it the complete code? Where is your update/upsert statement? Also are you doing this in the trigger? Commented Dec 31, 2018 at 6:51
  • This is the only change to the code that was made. It does not require an update/upsert statement. I've tried in both a trigger and a class, same result in both. The first code updates the record, the second does not. Commented Dec 31, 2018 at 6:55
  • Where are you getting the records in PetList? Is it something which you are assigning from Trigger.new? Commented Dec 31, 2018 at 7:03

2 Answers 2

2

PetList would have been aliased from Trigger.new in the first case, but in the second, it is a record from the database, a separate record in memory. The equivalent code would look something like:

for(Pet__c P :[SELECT ID,
               Type__c,
               Age__c, 
               FROM Pet__c
               WHERE ID IN :PetList]){
    if(P.Type__c == 'Cat'){
        Trigger.newMap.get(p.id).Age__c = 4;
    }
}

If you want to save data without a DML operation in a trigger class or trigger helper class, you must modify Trigger.new.

1

In the first code snippet, PetList has been assigned the Trigger.new which means it's is referencing the Trigger.new and in the before trigger context, Salesforce allows you to modify field values on the fly in Before context.

In the second code snippet you are querying records explicitly so you will have to call Update statement to perform an update.

From the documentation

Trigger.new - Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.

If you are performing a query then you will have to update those records explictly but that's not a good practice in Before context. Here is the doc reference which has explained everything you want to know. Context Variable Considerations

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.