0

I just start to learn Salesforce and now I try to create VisualForce page that display info about primary contact. I tried to use {!Opportunity.OpportunityContactRoles.Contact.Name}, but that way I can add only all related contacts. Maybe you should advice how I can add only primary contact? Maybe I should write my own controller?

I wrote this Extension:

public with sharing class opportunityControllerExtensionForPDF {

    private final Opportunity opportun;

    public opportunityControllerExtensionForPDF(ApexPages.StandardController stdController) {
        this.opportun = (Opportunity)stdController.getRecord();
    }

    @AuraEnabled(cacheable=true)
    public ID getPrimaryContactId() {
        OpportunityContactRole ocr = [
            SELECT Id, ContactId
            FROM OpportunityContactRole 
            WHERE (isPrimary=True 
            AND OpportunityId = :opportun.Id)
            WITH SECURITY_ENFORCED
            LIMIT 1
       ];
        return ocr.ContactId;
    }

    @AuraEnabled(cacheable=true)
    public Contact getPrimaryContact() {
        Id conId = getPrimaryContactId();
        return [
            SELECT Name, Phone, Email 
            FROM Contact 
            WHERE Id = :conId 
            WITH SECURITY_ENFORCED
            LIMIT 1
       ];
    }
}

Also I wrote such string in Visualforce:

<apex:outputText value="{!primaryContact.Phone}" />

But I see this message instead of Visualforce page: List has no rows for assignment to SObject

Where I made a mistake?

4
  • 1
    You will need a query of OpportunityContactRoles with a WHERE clause to get the primary Contact - so, you are right, for VF, you will need a controller extension to do this
    – cropredy
    Commented Jun 18, 2022 at 16:17
  • How did you invoke the VF page? Did you provide an id parameter with value of an Opportunity.Id?
    – cropredy
    Commented Jun 19, 2022 at 18:04
  • Thank you for your help. I understand my mistake.
    – Yauheni
    Commented Jun 21, 2022 at 17:57
  • Please post an answer to help the next person in the Community with a similar issue
    – cropredy
    Commented Jun 21, 2022 at 20:25

1 Answer 1

0

I find answer for this question thanks to @cropredy. The mistake was because I didn't get id from current page.

this.oppId = ApexPages.currentPage().getParameters().get('Id');

Also in my methods I need to return first element because SOQL return an array. For example:

return ocr.get(0).ContactId;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .