Tuesday, April 9, 2013

Account Owner on Opportunity:

Account Owner on Opportunity:
This is simple requirement need a lookup owner link on Account and populate this value with a trigger and create a formula field (Account.Owner_Link__r.FirstName +" "+ Account.Owner_Link__r.LastName) on Opportunity .
trigger Update_OwnerLink_on_Owner_Update1 on Account (before update, before insert) {

  // When 'Owner' field is changed, update 'OwnerLink' too

    // Loop through the incoming records
    for (Account o : Trigger.new) {

        // Has Owner chagned?
        if (o.OwnerID != o.Owner_Link__c) {
            o.Owner_Link__c = o.OwnerId;
        }
    }
}


@isTest(SeeAllData=true) public with sharing class TriggerTest_OwnerLink {       static TestMethod void testOwnerLink() {           // Grab two Users         User[] users = [select Id from User  where IsActive=True limit 2 ];         User u1 = users[0];         User u2 = users[1];           // Create an Opportunity         System.debug('Creating Account');         Account o1 = new Account(Name = 'Test Account',
Region__c='10',Global_Customer__c='Test',Industry_Rank__c=99, OwnerId = u1.Id);         insert o1;           // Test: Owner_Link should be set to user 1         Account o2 = [select id, OwnerId, Owner_Link__c from Account where Id = :o1.Id];         System.assertEquals(u1.Id, o2.OwnerId);         System.assertEquals(u1.Id, o2.Owner_Link__c);           // Modify Owner         o2.OwnerId = u2.Id;         update o2;           // Test: Owner_Link should be set to user 2         Account o3 = [select id, OwnerId, Owner_Link__c from Account where Id = :o2.Id];         System.assertEquals(u2.Id, o3.OwnerId);         System.assertEquals(u2.Id, o3.Owner_Link__c);     } }