• Nathan Barton
  • NEWBIE
  • 0 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

I'm currently trying to create a trigger that runs whenever an Opportunity is created or updated. The trigger needs to check all the other Opportunities related to the Account of the Opportunity being updated. It should check to see if any of the Opportunities have a StageName equal to 'Closed Won - One Time' or 'Closed Won - Recurring' and if so, it should update the account Type to 'Customer'. If none of the Opportunities are closed won, the Account Type should be 'Prospect'.

This is the code I have but I'm not sure if I'm querying the right things: 

trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    List<Account> accts = new List<Account>();
    List<Opportunity> opps = new List<Opportunity>(); 
    
    for (Opportunity opp : Trigger.new) {
        accts = [SELECT Id, Name, Type FROM Account WHERE Id =: opp.AccountId LIMIT 1]; 
        opps = [SELECT Id, AccountId, StageName, Account.Type FROM Opportunity WHERE AccountId =: opp.AccountId];
    }

    for (Account a : accts) {
        for (Opportunity o : opps) {
            if (o.StageName == 'Closed Won - One Time' || o.StageName == 'Closed Won - Recurring' || o.StageName == 'Customer Reseller') {
                if (a == null) {
                    a = new Account(Id = o.AccountId, name='TestingName');
                }
                a.Type = 'Customer'; 
            } else {
                a.Type = 'Prospect';
            }
        }
    }
    update accts;
}
Any help is much appreciated.

Cheers
  • August 12, 2014
  • Like
  • 0