Monday, August 21, 2017

Trigger to Sync the Quote with Opportunity

In Salesforce, quotes are a representation of prices that have been proposed to a customer for products or services.

An opportunity may have lots of quotes associated to it but only one quote may be synced to an opportunity at a time. Quote syncing links a quote a specific opportunity which allows updates to update between the Opportunity and Quote. Basically, when an Opportunity is added or removed it can be removed from the list of Opportunity Products without having to write any code. Keep in mind that this means Opportunity Products will be automatically removed and readded.

After an opportunity is synced to a quote there’s a few changes that will happen:

  • The Synced Quote is set
  • The Syncing checkbox on the Quote is set.
  • The Quote Products and Opportunity Products are merged.
  • The Opportunity Amount becomes readonly to the user regardless of whether a quote is currently syncing or not.
For the most part, if you are automatically creating quotes and emailing them it’s really trivial to sync the quote automatically.

Quotes can be synced manually, and pretty easily, but it can be automated very easily saving sales staff dozens of clicks a day if your sales process is very short.

Here’s a very simple example of how to do it in a trigger:

trigger QuoteTrigger on Quote (before update, before insert, after update, after insert) {
// for ease of example we're not going to use a trigger framework because it would make the example 100x longer.
// Logic shouldn't be in a trigger.

  if (Trigger.isInsert) {
        if (System.isAfter) {
            QuoteService qs = new QuoteService();
            qs.SyncQuotes(Trigger.new);
        }
    }
}

public with sharing class QuoteService {
public void SyncQuotes(List<Quote> quotes) {
List<Opportunity> opps = new List<Opportunity>();

// Loops through the List of Quotes and gets the OpportunityId.
for (Quote q : quotes) {
       if (string.isNotEmpty(q.OpportunityId) {
            Opportunity opp = new Opportunity(Id = q.OpportunityId);
             opp.SyncedQuoteId = q.Id;
             opps.add(opp);
         }
 }
  if(!opps.isEmpty()) {
          update opps;
     }
   }
}

No comments:

Post a Comment