function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
doubleminusdoubleminus 

Why won't this code work?

Why doesn't this code work?

 

Class:

 

	public static void changeVal(String id) {
		Case cas = [select id, val_flag__c, Requisition_Number__c, debug__c from Case where id=:id];

		cas.Requisition_Number__c = '8888';
		
		System.debug(cas.Id + ' <--- ID of record being manipulated');
	}
}

 

 

Trigger:

 

trigger trigPull on Case (before update) {

    Case[] cases = Trigger.new;
    
    pullApprover.changeVal(Trigger.new[0].Id);

    System.debug(Trigger.new[0].Id + ' <--- ID of record being manipulated');
}

 

 

Nothing happens. The Requisition_Number__c field does not get updated.

 

I'm not just looking for a fix, I'm also looking to see why this doesn't work.

 

The System.debug statements return the correct IDs of the record I want to change...

ngabraningabrani

I think you need to call upsert to update the changes in the database. Something like this should work -

 

     public static void changeVal(String id) {
         Case cas = [select id, val_flag__c, Requisition_Number__c, debug__c from Case where id=:id];
 
         cas.Requisition_Number__c = '8888';
         upsert(cas);
         
         System.debug(cas.Id + ' <--- ID of record being manipulated');
     }

In the code you had posted, cas was a local variable. After the end of the function the local variable dies without updating the database.

 

doubleminusdoubleminus

Thanks for the reply.

 

Adding an upsert causes an exception to be thrown (record updates --> code to update record updates record --> record updates --> code to update record updates record --> infinity)

 

I guess my question is...why is an update or upsert statement needed? The Apex Developer's documentation Hello World example just uses a local variable:

 

 

// This class updates the Hello field on account records that are  
    
// passed to it.  
    
public class MyHelloWorld {

   public static void addHelloWorld(Account[] accs){

      for (Account a:accs){
         if (a.Hello__c != 'World') {
            a.Hello__c = 'World';
         }
      }
   }
}

 

And it works fine to update a field...no update statement needed.

 

doubleminusdoubleminus

Anyone?

SuperfellSuperfell

In the docs example, the code is manipulating the objects in the Triggers.new collection, this is the data that goes onto to the db. In your version, you're querying a row, and manipulating the query result, not the trigger.new data.