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

Subsequent calls to inserts records instead of updating current record

I encountered some unexpected behavior with the save() method on the standard controller and just curious as to the reasoning behind it.


I have an instance of a StandardController for a new custom object.  Calling the save() method successfully inserts a new record for the custom object.  If you call save() again, it inserts another new record instead of updating the existing one in the controller's context.


Here's the basic code:


MyObject__c o = new MyObject__c();
ApexPages.StandardController sc = new ApexPages.StandardController(o);

// this successfully inserts a new record...;

// this successfully returns the Id of the new record
// doesn't this mean that the record is in the controller's current context?

Id myId = sc.getId();

// shouldn't this update the record that is in the current context?
// it does not; it inserts a new record;


Why doesn't the second call to save() update the record that was inserted in the first call to save()?   It seems to be holding on to the reference of the object that was passed into the constructor.  This would kind of make sense to me if the call to getId() returned null.  At least it would appear that the context of the controller is consistent.

Ritesh AswaneyRitesh Aswaney

I would blame it on . Get rid of the initialization to new, and only initialise it once in the contrctor as

MyObject__c c = (MyObject__c) sc.getRecord();

MyObject__c o = new MyObject__c();