+ Start a Discussion
uma52551.3972270309784705E12uma52551.3972270309784705E12 

Apex trigger to update account rating when the opportunity stage equals closed won

Can any one help me writing the trigger for upating the account rating field to 'hot' when the oppty stage is equal to 'closed won'?

thanks in advance...
Best Answer chosen by uma52551.3972270309784705E12
uma52551.3972270309784705E12uma52551.3972270309784705E12
Got the Answer For this.. Please let me know if any one needs the soultion for this..

All Answers

ShashForceShashForce
Hi,

Here is a sample code:

trigger updateAccountRating on opportunity (after insert, after update){
	list<Id> accIds = new list<Id>();
	list<Account> accounts = new list<account>();
	for(opportunity o:trigger.new){
		accIds.add(o.accountId);
	}
	for(account a:[select Id, Rating from account where Id IN :accIds]){
		for(opportunity opp:trigger.new){
			if(opp.stage=='closed won'){
				a.Rating='hot';
				accounts.add(a);
			}
		}
	}
    update accounts;
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
uma52551.3972270309784705E12uma52551.3972270309784705E12
Hi Shashank,


Thank you very much for your great help. If you don't mind can you please help me in writting the test class as well.
ShashForceShashForce
This is a very basic sample test class. You may have to change it a little and add more test methods for your specific requirements:

@istest
public class testClassForTrigger{
	public void testmethod triggerTest{
		account acc = new account();
		acc.name='test';
		opportunity opp = new opportunity();
		opp.name='test opp';
		opp.stagename='closed won';
		
		test.startTest();
		insert acc;
		insert opp;
		system.assertequals(acc.Rating,'hot');
		test.stopTest();
	}
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
uma52551.3972270309784705E12uma52551.3972270309784705E12
Wow! Thank you very much for this.


I am having the similar problem with another trigger which I wrote. Can you please check this and please let me knwo what is my mistake. (Don't Mind)


Apex Trigger for Updating Contact Owner same as the Account Owner:

trigger BUIContactOwnerUpdateTrigger on Contact (before insert, before update) {

List <RecordType> rtList = [SELECT Id from RecordType where SobjectType='Contact' and Name='BUI' Limit 1];
List <Id> AccountIds = new List <Id>();
Map<Id,Id> accountOwnerIdMap = new Map<Id,Id>();
for(Contact c : trigger.new)
{
if(c.AccountId !=NULL)
AccountIds.add(c.AccountId);

System.debug('Adding Account Id:'+c.AccountId);
}
List<Account> accountList = [SELECT Id,ownerId from Account WHERE Id IN :AccountIds];

for(Account acc : accountList){
accountOwnerIdMap.put(acc.Id, acc.ownerId);

}
for(Contact c:trigger.new){
System.debug('The Record Type list Id:' +rtList[0].Id);

if(c.recordTypeId ==rtList[0].Id)

    c.ownerId = accountOwnerIdMap.get(c.accountId);
  
System.debug('To Know contact OwnerId :'+c.OwnerId);    
}
}
}


Apex Test Class for the above Trigger:

@isTest
private class TestBUIContactOwnerUpdateTrigger {

    static testMethod void myTestUpdate() {
       
        Account a = new Account(Name = 'Test Account TA1');
     
         User user1 = [Select Id from User where FirstName = 'XYZ' AND LastName = '1234' Limit 1];
         a.ownerId =user1.Id;
           insert a;
            
        Contact c1 = new Contact(AccountId=a.Id,lastname='Test1',recordTypeId='012E00000001sCE',firstname='Contact', OwnerId=user1.Id);
         insert c1;
                       
                      System.assertEquals(c1.ownerId,a.ownerId);       
            
       User user2 = [Select Id from User where FirstName = 'ABC' AND LastName = '3456' Limit 1];
  
            
        Contact c2 = new Contact(AccountId=a.Id,lastname='Test2',recordTypeId='012E00000001sCE',firstname='Contact', OwnerId=user2.Id);
      
                      insert c2;
                   
                      System.assertEquals(c2.ownerId,a.ownerId);
                    
     
                
                 }                   
}


Assertion is not working gor the second contact. First contact was good, by this it is not passing the test.. please help me in finnding the bug in my code.
ShashForceShashForce
Instead of querying for users, please try to insert a test user like you inserted account and contact, and use that user for assertion.
uma52551.3972270309784705E12uma52551.3972270309784705E12
Even if  I am inserting the new users it is throwing the same exception Expected is something and actual is different. Please check the below modifed code:


@isTest
private class TestBUIContactOwnerUpdateTrigger {

    static testMethod void myTestUpdate() {
        
  
         Profile p = [select id from profile where name ='standard user'];
        User user1 = new User(alias = 'test123', email='test123@noemail.com',
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, country='United States',
            timezonesidkey='America/Los_Angeles', username='test123@noemail.com');
        insert user1;
             
           User user2 = new User(alias = 'test456', email='test456@noemail.com',
            emailencodingkey='UTF-8', lastname='Testing2', languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, country='United States',
            timezonesidkey='America/Los_Angeles', username='test456@noemail.com');
        insert user2;
       
         Account a = new Account(Name = 'Test Account TA1');
         a.ownerId =user1.Id;
          insert a;

        Contact c1 = new Contact(AccountId=a.Id,lastname='Test1',recordTypeId='012E00000001sCE',firstname='Contact', OwnerId=user1.Id);
         insert c1;
               System.assertEquals(c1.ownerId,a.ownerId);        
                  System.debug('After assertion:' + c1.ownerId);
      
              System.debug('Before assertion:' + a.ownerId);
        Contact c2 = new Contact(AccountId=a.Id,lastname='Test2',recordTypeId='012E00000001sCE',firstname='Contact', OwnerId=user2.Id);
                     
                                            insert c2;
                      System.debug('Contact accoutId:' + c2.accountId);
        
                      System.assertEquals(c2.ownerId,a.ownerId);
                     
                      System.debug('After assertion:' + c2.ownerId);
                 
                 }                    
}
ShashForceShashForce
Please try inserting both contacts at once using a list. Something like:

Contact c1 = new Contact(AccountId=a.Id,lastname='Test1',recordTypeId='012E00000001sCE',firstname='Contact', OwnerId=user1.Id);
Contact c2 = new Contact(AccountId=a.Id,lastname='Test2',recordTypeId='012E00000001sCE',firstname='Contact', OwnerId=user2.Id);
list<contact> ContactList = new list<contact>();
ContactList.add(c1);
ContactList.add(c2);
insert ContactList;
uma52551.3972270309784705E12uma52551.3972270309784705E12
Showing the same error for the assertions:

System.assertEquals(ContactList[0].ownerId,a.ownerId);                  
System.assertEquals(ContactList[1].ownerId,a.ownerId);

System.AssertException: Assertion Failed: Expected: 005f00000010hCLAAY, Actual: 005f00000010hCKAAY
uma52551.3972270309784705E12uma52551.3972270309784705E12
Hi Shashank,

The Account Rating trigger is not working can you please help to find out the bug or I am missing some thing?
trigger BBWGUpdateAccountRating on Opportunity (after insert,after update) {
List <RecordType> rtList = [SELECT Id from RecordType where SobjectType='Opportunity' and Name='BBWG' Limit 1];
set<ID> AccountIDs = new set<ID>();
for(Opportunity o : Trigger.new){
    if(o.StageName == 'Closed Won'){
    AccountIDs.add(o.accountid);
    System.debug('Account Id:'+ o.accountId);
    }
}
list<Account> accounts = new list<account>();
for(account a:[select Id, Rating from account where Id IN :AccountIDs]){
        for(opportunity opp:trigger.new){
            if(opp.stageName=='closed won'){
                a.Rating='hot';
                accounts.add(a);
            }
        }
    }
    update accounts;
}

ShashForceShashForce
Looks okay to me, can you tell me what exactly is not working, so that I can understand better?
uma52551.3972270309784705E12uma52551.3972270309784705E12
The test is not getting passed assertion failure it is showing here   I am pasting the test class please check that as well

@isTest
private class TestBBWGUpdateAccountRatingTrigger {

    static testMethod void myTestUpdateRating() {           
         Opportunity o = new Opportunity(Name = 'New Oppty NP1',stageName='Closed Won',recordTypeId='012E00000001AtQ',closeDate=Date.today());
         insert o;       
         Account a = new Account(Name = 'Test Account TA2',rating = 'Cold',recordTypeId='012E00000001Ata',Id = o.accountId);
         insert a;      
         System.debug('Before Assertion:'+a.rating); 
         System.assert(a.rating=='Hot');
         update a;
         System.debug('After Assertion:'+a.rating); 
                               
     }                    
}
uma52551.3972270309784705E12uma52551.3972270309784705E12
Even when I am trying to fetch the account Id it is showing as null
ShashForceShashForce
Hi,

You should insert the account record first and then insert the opportuniity record, since the trigger is on the opportunity object. Please try something like this:

@isTest
private class TestBBWGUpdateAccountRatingTrigger {

    static testMethod void myTestUpdateRating() {           
                
         Account a = new Account(Name = 'Test Account TA2',rating = 'Cold',recordTypeId='012E00000001Ata');
         insert a;
		 Opportunity o = new Opportunity(Name = 'New Oppty NP1',stageName='Closed Won',recordTypeId='012E00000001AtQ',closeDate=Date.today(),accountId=a.Id);
         insert o;
         System.debug('Before Assertion:'+a.rating); 
         System.assert(a.rating=='Hot');
         System.debug('After Assertion:'+a.rating); 
                               
     }                    
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
uma52551.3972270309784705E12uma52551.3972270309784705E12
Yes It is showing the same error asserton failed. 
uma52551.3972270309784705E12uma52551.3972270309784705E12
Got the Answer For this.. Please let me know if any one needs the soultion for this..
This was selected as the best answer
s shekar 19s shekar 19
it is working only for after insert but it is not working for after update can you please check this once? if i edit the opportunity stagename to closed lost,the account the rating will be hot itself.then how we can meet the requirement?

Thanks in Advance 
smriti sharan19smriti sharan19
Below is the code:
 
trigger updateRatingAccount on Opportunity(after update ) {

Set<id> setaccid = new Set<id>();
List<Account> newacclist = new List<Account>();

 for (Opportunity opp : Trigger.new) {
        if(opp.StageName=='Closed Won' && opp.accountid !=null
        && opp.StageName!=Trigger.OldMap.get(opp.id).StageName
         ){
            setaccid.add(opp.accountid);
            }
     
    List<Account> acclist = [Select id,rating from account where id IN: setaccid];
     for(Account acc:acclist){
         acc.rating = 'Hot';
         newacclist.add(acc); 
     }
     }
     update newacclist;
}

Hope it helps.

Thanks
Smriti Sharan