Does changing ownership of an account through apex automatically change ownership of related records like opportunity, contact etc?
While making the change through UI, there is a text which says these related records would change and there are checkboxes to select the change of related records.
Would these related records change or do we need to change them from apex? Does the email for ownership also need to written in apex while changing through code?
First off, we need to understand how Ownership works and how it effects Sharing
Each record is owned by a user or optionally a queue for custom
objects, cases and leads. The record owner is automatically granted
Full Access, allowing them to view, edit, transfer, share, and delete
When looking at the different types of relationships (lookup and master-detail) and how they effect ownership, we know:
Master-Detail (1:n) — A parent-child relationship in which the master object controls certain behaviors of the detail object:
- The Owner field on the detail object is not available and is automatically set to the owner of its associated master record. Custom
objects on the detail side of a master-detail relationship cannot have
sharing rules, manual sharing, or queues, as these require the Owner
- The detail record inherits the sharing and security settings of its master record.
Lookup (1:n) — This type of relationship links two objects together, but has no effect on deletion or security. Unlike
master-detail fields, lookup fields are not automatically required.
When you define a lookup relationship, data from one object can appear
as a custom related list on page layouts for the other object. See the
Salesforce online help for details.
Second, let’s take a look at the Account documentation and the field that needs to changed to transfer ownership. From the Account documentation:
Properties Create, Defaulted on create, Filter, Group, Sort, Update
Description The ID of the user who currently owns this account. Default value is the user logged in to the API to perform the create.
If you have set up account teams in your organization, updating this
field has different consequences depending on your version of the API:
- For API version 12.0 and later, sharing records are kept, as they are for all objects.
- For API version before 12.0, sharing records are deleted.
- For API version 16.0 and later, users must have the “Transfer Record” permission in order to update (transfer) account ownership
using this field.
However, from what we understand on how record ownership, we know that these ownership changes must have done outside of the normal OwnerId change (which is why they would even allow them to be optional). All the OwnerId truly controls is the Account owner and their subsequent child objects from a Master-Detail relationship. This means that to transfer opportunities, transfer cases, send a notification email, etc must all be handled manually in your Apex code.