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
Test999999Test999999 

Update without fetching

If I already know the id and fields I want to update, do I have to fetch the records first ?

 

I tried just  allocating a obj and populating it with the details: 

 

CustomObj__c = new CustomObj__c();

c.Id = idToUpdate;

c.Field1__c = 'New Value'

 

The problem is that the Id field in not writeable.

 

I want to avoid the Select / Fetch if possbile.  Suggestions ?

 

Thanks,

 

Best Answer chosen by Admin (Salesforce Developers) 
hisrinuhisrinu

CustomObj__c = new CustomObj__c(Id = idToUpdate);

c.Field1__c = 'New Value';

update c;

 

This should work (assuming you are going to replace the value in field1__c)

All Answers

bob_buzzardbob_buzzard

If you have an external id field on your object and you have the value for that, you could use the upsert DML method.  Aside from that, I think you'll have to execute SOQL to get the ids filled in.  Assuming that you have the ids in question in a list, you can do it in a single SOQL statement.  Not ideal, but not too arduous.

Always ThinkinAlways Thinkin

Hi,

It actually does work to update an object's record by referencing its ID field as you've done. The Update call will update all fields on the record referenced by the ID you provide even though you cannot write to the ID field itself.

 

If you're getting specific errors with your code, post a snippet here (the code you've got below has a couple obvious errors, but I assume that was just some psuedo code for example purposes).

 

Luke C

hisrinuhisrinu

CustomObj__c = new CustomObj__c(Id = idToUpdate);

c.Field1__c = 'New Value';

update c;

 

This should work (assuming you are going to replace the value in field1__c)

This was selected as the best answer