A short, reusable Apex approach to copy non-null fields from a child SObject (Opportunity) into a parent (Account) using a single generic utility method.
Problem
When copying values from a related child object to a parent record (for example, Opportunity -> Account), developers often write repetitive if-checks to copy each field only when the source value is not null. This becomes unmaintainable as the number of fields grows.
Solution overview
Use SObject’s dynamic API (SObject.put and field API names) with a small utility method that only writes a value when it is non-null. The same method can be reused across objects and fields, reducing redundancy and improving readability.
Utility method
Put this helper in a shared utility class used by your trigger handlers:
public class SObjectUtils { public static void updateFieldIfNotNull(SObject record, String fieldName, Object fieldValue) { if (fieldValue != null) { record.put(fieldName, fieldValue); } } }
Example usage (Opportunity -> Account)
Within your trigger helper where you already have the latest (old) Opportunity fetched and the new Opportunity from trigger context, call the utility for each field to copy:
// assume acc is Account SObject, newOppy is Opportunity SObject if (oldOppy.Id == newOppy.Id) { SObjectUtils.updateFieldIfNotNull(acc, 'Field_1__c', newOppy.get('Field_1__c')); SObjectUtils.updateFieldIfNotNull(acc, 'Field_2__c', newOppy.get('Field_2__c')); SObjectUtils.updateFieldIfNotNull(acc, 'Field_3__c', newOppy.get('Field_3__c')); SObjectUtils.updateFieldIfNotNull(acc, 'Field_4__c', newOppy.get('Field_4__c')); }
Best practices and considerations
- Use actual API field names and avoid hard-coding labels.
- When copying many fields, consider storing mappings in a config (Custom Metadata or a Map) and iterating over them rather than calling updateFieldIfNotNull repeatedly in code.
- Mind field-level security and running mode — use WITH SECURITY_ENFORCED or appropriate checks if needed.
- For complex type conversions (Date, Lookup Ids, Enums), validate or convert values before calling the helper.
Why this matters
This small pattern dramatically reduces code duplication and makes field-mapping logic easier to maintain and reuse across objects and triggers — especially when mapping dozens of fields or when mapping from different source objects (Case, Opportunity, custom objects).
For Salesforce admins and developers, using SObject dynamic methods and a tiny utility reduces bugs, speeds up reviews, and simplifies future changes to mapping logic.
Leave a Reply