You need to sign in to do that
Don't have an account?
Database.update not updating related object field
Hi there,
I have the following test code which updates a field in a related object (CustomObject__r). The CustomObject is related to Opportunity and the code below runs through successfully.
Opportunity o = [select CustomObject__r.Market__c,StatusMessage__c from Opportunity where Id='00600000008HFNLAA5'];
o.CustomObject__r.Market__c = 'test';
o.StatusMessage__c = 'test update';
try
{
Database.SaveResult srs = Database.update(o);
if (srs.isSuccess())
{
// successful
}
} catch (Exception e) {
ApexPages.addMessages(e);
}
The above code does not return an exception and also is successful based on the return value of isSuccess(). The StatusMessage__c in the main object is successfully updated, but the CustomObject__r.Market__c field does not get updated even though the update transaction as a whole is deemed successful. Any troubleshooting ideas, or if the above update is not possible (ie. have to fetch back and update CustomObject__c directly)?
thanks
Quoting the APEX reference (W11, page 223)
A single update statement can only modify one type of sObject at a time. For example, if updating an account field
through an existing contact that has also been modified, two update statements are required:
// Use a SOQL query to access data for a contact
Contact c = [select account.name from contact
where lastName = 'Carter' limit 1];
// Now we can change fields for both the contact and its
// associated account
c.account.name = 'salesforce.com';
c.lastName = 'Roth';
// To update the database, the two types of records must be
// updated separately
update c; // This only changes the contact's last name
update c.account; // This updates the account name
All Answers
Just to capture the exception if there is any, you can try this.
try
{
update o;
} catch (Exception e) {
System.debug('Exception is ' + e.getMessage());
ApexPages.addMessages(e);
}
Quoting the APEX reference (W11, page 223)
A single update statement can only modify one type of sObject at a time. For example, if updating an account field
through an existing contact that has also been modified, two update statements are required:
// Use a SOQL query to access data for a contact
Contact c = [select account.name from contact
where lastName = 'Carter' limit 1];
// Now we can change fields for both the contact and its
// associated account
c.account.name = 'salesforce.com';
c.lastName = 'Roth';
// To update the database, the two types of records must be
// updated separately
update c; // This only changes the contact's last name
update c.account; // This updates the account name
Ah got it, thanks for the pointer!