How can I use the “trigger.new” and “trigger.newmap” for validating the records?

276    Asked by CharlesParr in Salesforce , Asked on Feb 5, 2024

 In the context of the Salesforce apex trigger I have a scenario where I have a custom object with a before-update trigger. How can I use the “trigger.new” and “trigger.newmap” for validating and updating the records based on a particular field during the time of web records being updated? 

Answered by Delbert Rauch

 In the context of Salesforce, let us consider that you have a custom object whose name is “CustomObject___c” with a related field “relatedField__c”. You aim to enforce a rule related to validation and updating the records based on the value of “relatedField__c” during a before-update trigger.

Here is the example given of how you can achieve this particular target:-

Trigger CustomObjectTrigger on CustomObject__c (before update) {

    // Map to store the old values of RelatedField__c
    Map oldRelatedFieldMap = new Map();
    // Populate the oldRelatedFieldMap with the old values of RelatedField__c
    For (CustomObject__c oldRecord : Trigger.old) {
        oldRelatedFieldMap.put(oldRecord.Id, oldRecord.RelatedField__c);
    }
    // Iterate over the records being updated
    For (CustomObject__c newRecord : Trigger.new) {
        String oldRelatedFieldValue = oldRelatedFieldMap.get(newRecord.Id);
        String newRelatedFieldValue = newRecord.RelatedField__c;
        // Validation rule: Example – Ensure RelatedField__c is not being changed
        If (oldRelatedFieldValue != newRelatedFieldValue) {
            newRecord.addError(‘RelatedField__c cannot be changed.’);
        }
        // Update logic: Example – Set another field based on the value of RelatedField__c
        If (newRecord.RelatedField__c == ‘SpecificValue’) {
            newRecord.AnotherField__c = ‘UpdatedValue’;
        }
    }}


Your Answer

Interviews

Parent Categories