Header Ads Widget

Trigger Scenario 2 on before Update with Trigger.old, after update a old record that old record will create in its parent object

Trigger Scenario 2 on before Update with Trigger.old, after update a old record that old record will create in its parent object
Trigger Scenario 2 on before Update with Trigger.old
When ever customer record is updated, before updating the record new record in test object with old values of customer record.
Before write trigger code we must have two objects and its fields.
Objects:
-         Customer(its API Name: Customer__c)
-         Test(its API Name: Test__c)
Customer object must have bellow fields
-         Customer Name(its API Name: Name)
-         Salary(its API Name: Salary__c)
-         Phone(its API Name: Phone__c)
-         Test(Lookup field in Customer object its API Name: Test__c)
Test object must have bellow fields
-         Test Name(its API Name: Name)
-         Salary(its API Name: Salary__c)
-        Phone(its API Name: Phone__c)
Trigger:
Create Trigger in Developer Console with the name ‘CustomerUpdate’.
trigger CustomerUpdate on Customer__c (before Update) {
    List test = new list();
    for(customer__c x: trigger.old){
        Test__c t = new Test__c();
        t.name = x.name;
        t.salary__c = x.salary__c;
        t.Phone__c = x.Phone__c;
            test.add(t);
    }
    insert test; 
}

Output:

How to see output

Create a record on Customer object and open that record

OR

Open previus record on Customer object like bellow
NOW CLICK ON EDIT BUTTON

Change the values, here we have to remember  name value(‘Rambabu’---> old value) and click on Save Button
AFTER CLICK ON SAVE BUTTON AND GO THE TEST OBJECT
CLICK GO BUTTON

We can see record before updated Customer record with old values in test object like bellow

Test Class:
 @isTest

public class CustomerUpdateTest {

    Static testMethod void testcustomer(){

        Customer__c x = new Customer__c();

        x.name = 'Satya';

        x.salary__c = 1000;

        x.phone__c = '123456';

        insert x;

        test__c t = new Test__c();

        t.name = x.name;

        t.phone__c = x.phone__c;

        t.salary__c = x.salary__c;

        insert t;

        System.assertEquals(t.name, x.name);

        System.assertEquals(t.salary__c, x.salary__c);

        x.name = 'Satya k';

        x.salary__c = 3000;

        update x;
       
   }

}


Post a Comment

0 Comments