Archive | Apex Code RSS for this section

Adding a phone number field to Salesforce.com Opportunities

We recently had an InGenius Connector Enterprise customer who wanted to have clickable phone numbers associated with each opportunity.  By default, opportunities don’t have any phone number fields.

The customer’s workflow was that they wanted their workers to go through the opportunities, and call each one every few days, until the sales was closed.

The Solution:

We advised the customer to add a field to the opportunity of type “Phone.”  We called this field “Account Phone.” Since this field is of type “Phone,” it will automatically be converted to a “click-to-dial” field by InGenius Connector Enterprise.

We then added a trigger to the Account that detects any changes, and then loops through all the opportunities associated with this account, and updates the “Account Phone” field in all the opportunities.

This way, the opportunities all have a clickable phone number field that stays in sync with the phone number field in the Account.

The Trigger Apex Code:

trigger UpdateOpportunityPhoneField on Account (after insert, after update) {
  // Loop through all account updates in this trigger (there will generally be one)
  for(Account acct: Trigger.new) {
    List<Opportunity> oppList = [SELECT id, Account_Phone__c FROM Opportunity WHERE Accountid = :acct.id AND Account_Phone__c != :acct.Phone]; // Find all the opportunities for this account.
    for(integer i = 0 ; i < oppList.size(); i++){
      oppList[i].Account_Phone__c = acct.Phone; // Update all opportunities with the new phone number.
    }
    update oppList;
  }
}

Things to be aware of:

  • The solution uses some Apex code to accomplish its magic. You’ll need an appropriate Salesforce.com subscription to use this solution.
  • The code loops through all the Opportunities each time an Account is changed. This could use up your Apex allowance.
  • If the user edits the Account Phone field in the Opportunity, this is not copied back up to the Account. You could add a second trigger for this, if needed. If the user edits the Account Phone field, the changes will be wiped out the next time the Account is edited. Another alternative is to make the Account Phone field read-only in the Opportunity Layout.