Visualforce Email Template with custom controller

Apex Controller:

public  class acctTemplt
{
    public Id accountId {get;set;}
    public List<Opportunity> getopptys()
    {
        List<Opportunity> oppty;
        oppty = [SELECT Name, StageName FROM Opportunity WHERE Accountid =: accountId];
        return oppty;
    }
}


Component:

Name:OpptyList

<apex:component controller="acctTemplt" access="global">
    <apex:attribute name="AcctId" type="Id" description="Id of the account" assignTo="{!accountId}"/>
    <table border = "2" cellspacing = "5">
        <tr>
            <td>Opportunity Name</td>
            <td>Opportunity Stage</td>               
        </tr>
        <apex:repeat value="{!opptys}" var="o">
        <tr>
            <td>{!o.Name}</td>
            <td>{!o.StageName}</td>             
        </tr>
        </apex:repeat>       
    </table>
</apex:component>


Visualforce Email template:

<messaging:emailTemplate subject="List of opportunity" recipientType="User" relatedToType="Account">
    <messaging:htmlEmailBody >
    Hi,<br/>
    Below is the list of opportunities for your account {!relatedTo.Name}.<br/><br/>
    <c:OpptyList AcctId="{!relatedTo.Id}" /><br/><br/>
    <b>Regards,</b><br/>
    {!recipient.FirstName}
    </messaging:htmlEmailBody>
</messaging:emailTemplate>


Output:



Cheers!!!

8 comments:

  1. Hi, this same stuff does NOT work for Event object if you put relatedToType="Event" in the VF template. Not even the "{!relatedTo.id}" is printing!!, not sure why SF designed it this way:(..great if you have a solution

    ReplyDelete
  2. Using this logic can we order a Opportunity Line Items into Categories like A,B,C in the Email Template,
    EX:
    it list as follows with ther Pricebook entry name.
    1a
    1b
    1c
    2a
    2b
    2c
    But i need something like this
    1a
    2a
    1b
    2b
    1c
    2c

    ReplyDelete
    Replies
    1. Use map data type to group. Map>.

      Cheers!!!

      Delete
    2. Thanks for reply ,
      Can you give me an example with the map for my need.

      Delete
  3. Hi - This is great. Very helpful. One question: does the component class need to be tested? What would a test look like for a class this simple/small?

    ReplyDelete
  4. I have scenario populate Account Billing Address To Related list contact mailing address by using custom button with java script How?

    ReplyDelete
  5. Hi,
    can we call Salesforce standard email template(like 'send an email' in activity history) from our vf page.

    ReplyDelete