[SalesForce] How to update a record but not overwrite a specific field

I have an Account(Name='Hello') and the following code

// First get an Account with its Name field and some other fields
Account acc = [SELECT Id, Name, Otherfields FROM Account WHERE Id = ...];
// acc.Name is 'Hello'

// Now some other code that loads the Account, changes the Name field to 'Hello' and updates the Account
someFunctionThatChangesAccountName(acc.Id);
// In DB, the Account will now have the Name 'World'
// The local acc variable will still hold the Name 'Hello'

// Now here I want to change some other fields, then update the Account
acc.OtherField__c = ...;
update acc; // Oh no, acc.Name is still 'Hello' and will overwrite 'World'

But now the Account will now contain 'Hello' again, because the latter update will overwrite the first 'World' Name update from someFunctionThatChangesAccountName.

So how can I update an Account, but not update the Name field?

PS: I know I could just simply pass the acc itself to the function and it would update the Name on the acc record, but in our code that is not possible because someFunctionThatChangesAccountName actually is not a function but a Trigger that runs when I change a Contact record. It fetches the Account, changes its name, then updates the Account.

Best Answer

Okay so if you can't update the function to accept & return the acc variable because it's a trigger or some other secondary process, then it might be easier to insert only the values you want to update:

// First get an Account with its Name field and some other fields
Account acc = [SELECT Id, Name, Otherfields FROM Account WHERE Id = ...];
// acc.Name is 'Hello'

// Now some other code that loads the Account, changes the Name field to 'Hello' and updates the Account
someFunctionThatChangesAccountName(acc.Id);
// In DB, the Account will now have the Name 'World'
// The local acc variable will still hold the Name 'Hello'

// create an empty account and map across only the fields you want to update
Account accToUpdate = new Account();
accToUpdate.Id = acc.Id;
accToUpdate.OtherField__c = ...;

update accToUpdate;
Related Topic