2

I have a Visualforce component issue that I cannot resolve.

VF page:

<apex:page standardController="Opportunity" extensions="MyExtension">
    <c:childComponent />
</apex:page>

Child component:

<apex:component>
    <apex:form>
        <apex:commandLink value="Cancel" action="{!doCancel}"></apex:commandLink>
    </apex:form>
</apex:component>

Extension class:

public with sharing class MyExtension {
    public Id recordId;

    public MyExtension(ApexPages.StandardController stdController) {
        this.recordId = stdController.getId();
    }

    public PageReference doCancel() {
        return new PageReference('/' + this.recordId);
    }
}

I need the command link in the child component to call the doCancel() method in the parent page's extension's class.

Is this possible?

1
  • 2
    +1 for a nice MVR of the issue
    – cropredy
    Jun 9, 2022 at 18:17

1 Answer 1

3

The solution is to modify your component markup

<apex:component>
  <apex:attribute name="cancelAction" type="ApexPages.Action" required="true"/> 
  <apex:form>
    <apex:commandLink value="Cancel" action="{!cancelAction}" immediate="true"/>
  </apex:form>
</apex:component>

and then reference the component as such:

<apex:page standardController="Opportunity" extensions="MyExtension">
  <c:childComponent cancelAction="{!doCancel}"/>
</apex:page>

Hat tip to Keir Bowden and his seminal book Visualforce Development Cookbook 2nd Edition p. 51

How this works:

You are passing to the component an object of type ApexPages.Action. A rarely-used explicit object type but especially handy in this use case.

1
  • This worked beautifully. Thanks a lot!
    – Will
    Jun 10, 2022 at 9:31

You must log in to answer this question.

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