Creating a Custom Component to Display Opportunity Contact Roles on Cases

When managing customer support or marketing a products, having quick access to the right contacts is crucial. Salesforce offers Contact Roles for Opportunities, but what if you want to view these roles directly from a Case record?

This functionality is especially helpful when your service team needs to identify key contacts for an opportunity from the case record without switching back and forth between records.

Why is This Useful?

Let’s say your support/marketing team receives a case for an important opportunity. By displaying the opportunity’s key contact roles (like decision-makers or influencers) directly on the case record, your agents can quickly see who to contact without leaving the case page.

Step-by-Step Guide

1. Define the Relationships

To build this, you’ll need to understand the standard relationship between the Case, Opportunity, and Contact Role objects.

  • Case: Linked to an Account.
  • Opportunity: Also linked to the Account.
  • Opportunity Contact Role: A junction object linking Opportunity and Contacts.

To connect these, the custom component will need to pull the related opportunities of the case and retrieve the contact roles associated with those opportunities. Thus, first of all, the case object needs to have a lookup relation to the opportunity object. This can be done by:

Step 1.1: Open Setup:
  • In Salesforce, Open the Setup by clicking on the gear icon from the toolbar.
Step 1.2: Add the field on Case object:
  • Go to the Object Manager Tab
  • Select Case
  • Select Fields and Relationships from the sidebar
  • Click “New” to create a new field on Case object
  • Select Lookup Relationship as the field Type
  • Select Opportunity as the Related to object
  • Use appropriate name for the Field Label and Field Name (NOTE: This API name would be used to refer to the Opportunity record when using the SOQL in the apex class)
  • Add appropriate Field-level security and Save

2. Build the Lightning Component

Step 2.1: Open Developer Console:
  • In Salesforce, click on your avatar in the top-right corner.
  • Select Developer Console from the dropdown menu.
Step 2.2: Create a New Lightning Component Bundle:
  • In the Developer Console, go to File > New > Lightning Component.
  • In the pop-up window, give your component a name (e.g., OpportunityContactRolesOnCase).
  • Select the options for how the component should be used:
    • Lightning Record Page (for record pages)
    • Lightning App Page
    • Lightning Tab
  • Click Submit
Step 2.3: Edit the Component (.cmp file):

After creating the component, the main component file (.cmp) will open automatically. Here’s where you define the structure and layout of your Lightning Component.

Add the code below to this File: Eg. OpportunityContactRolesOnCase.cmp
Note: CaseOpportunityContactRolesController should be same name as the controller in step 5

————————————————————————

<aura:component controller=”CaseOpportunityContactRolesController”

                implements=”flexipage:availableForAllPageTypes,force:hasRecordId”

                access=”global”>

    <!– Attribute to store the Contact Roles –>

    <aura:attribute name=”contactRoles” type=”List” />

    <!– Fetch the Contact Roles from the server-side controller –>

    <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” />

    <lightning:card title=”Opportunity Contact Roles” class=”contact-roles-card”>

        <!– Display a message if no Contact Roles are found –>

        <aura:if isTrue=”{!empty(v.contactRoles)}”>

            <p class=”slds-text-body_regular slds-p-around_medium slds-text-align_center”>No Contact Roles found.</p>

        </aura:if>

        <!– If Contact Roles exist, display them in a grid –>

        <aura:if isTrue=”{!not(empty(v.contactRoles))}”>

            <ul class=”slds-has-dividers_around-space slds-p-around_medium”>

                <aura:iteration items=”{!v.contactRoles}” var=”role”>

                    <li class=”slds-item slds-grid slds-wrap slds-p-around_x-small”>

                        <!– Icon and Contact Name –>

                        <div class=”slds-col slds-size_1-of-2 slds-grid slds-align_absolute-center”>

                            <lightning:icon iconName=”standard:contact” alternativeText=”Contact Icon” size=”small” class=”slds-m-right_x-small”/>

                            <!– Contact Name as clickable link –>

                            <lightning:formattedUrl label=”{!role.Contact.Name}” 

                                                    value=”{!’/’ + role.ContactId}” 

                                                    target=”_blank” 

                                                    class=”contact-link slds-text-heading_small”/>

                        </div>

                        <!– Contact Role –>

                        <div class=”slds-col slds-size_1-of-2 slds-text-align_right”>

                            <span class=”slds-text-body_small”>{!role.Role}</span>

                        </div>

                    </li>

                </aura:iteration>

            </ul>

        </aura:if>

    </lightning:card>

</aura:component>

————————————————————————

Step 2.4: Add the JavaScript Controller (.js file):

Now, define the logic in the JavaScript controller to call the Apex method that fetches the Opportunity Contact Roles
Add the Code below to this file: Eg. OpportunityContactRolesOnCaseController.js
————————————————————————

({

    doInit : function(component, event, helper) {

        // Fetch contact roles

        var action = component.get(“c.getContactRoles”);

        action.setParams({ caseId: component.get(“v.recordId”) });

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === “SUCCESS”) {

                component.set(“v.contactRoles”, response.getReturnValue());

            } else {

                console.error(“Failed to retrieve contact roles: ” + state);

            }

        });

        $A.enqueueAction(action);

    }

})

————————————————————————

Step 2.5: Create the Apex Controller (Apex Class):

.You’ll need a server-side Apex controller to fetch the Contact Roles related to the Opportunity.

  • In the Developer Console, go to File > New > Apex Class.
  • Name it something like CaseOpportunityContactRolesController.

Add the code below to this file: Eg. CaseOpportunityContactRolesController.apxc

Note: Opportunity__c should be the correct API name as defined in the Case object for the lookup field to Opportunity.
————————————————————————
public with sharing class CaseOpportunityContactRolesController {

    @AuraEnabled

    public static List<OpportunityContactRole> getContactRoles(Id caseId) {

        // Query the Case for its related Opportunity

        Case caseRecord = [SELECT Opportunity__c FROM Case WHERE Id = :caseId LIMIT 1];

        if (caseRecord.Opportunity__c != null) {

            // Return the Contact Roles for the related Opportunity

            return [SELECT ContactId, Role, Contact.Name 

                    FROM OpportunityContactRole 

                    WHERE OpportunityId = :caseRecord.Opportunity__c

                    AND ContactId != null];  // Ensure ContactId is not null

        }

        return new List<OpportunityContactRole>();

    }

}

————————————————————————

Step 2.6: Add Your Component to the Case Record Page:
  • Save your component, JavaScript controller, and Apex class.
  • You can now add the component to a record page

To do that:

  • Navigate to Setup > Object Manager > Case > Lightning Record Pages.
  • Open the Lightning Record Page where you want to display this component.
  • Drag and drop the component onto the record page layout from custom component list.
  • Save and activate the page.

Or

  • Go to the case record page where you want to add the component
  • Click the gear icon on top-right
  • Click edit page
  • Drag and Drop the component on the record page layout from custom component list
  • Save and Activate the page

Conclusion

With this custom Lightning component, your support team can now easily view and act on contact roles associated with related opportunities, improving efficiency and response times. This is a powerful way to bridge data between cases and opportunities, streamlining your case management process.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.