How to implement Visualforce Component with Attributes ?

A Developer wants to implement such functionality or code which is required in multiple visualforce pages. So instead of repeating  the same code again and again, we can create visualforce component. Then we can use visualforce component in every place where we need that particular piece of code. In other words, custom visualforce component allows us to create reusable component.

All custom visualforce component definitions must be wrapped inside a single tag . Here the component_Name is the named component and can be used inside visualforce page.

We can also use tag to use customize the component so that custom component can be used in different manners depending on value of different attributes. It helps us in creating reusable generic component and also saves time and number of lines we write in apex and visualforce page.

In the example below, we will learn to create a Visualforce Component which uses getter setter methods to showcase the value passed by Visualforce page.

Visualforce Page:- (ContactPage)

<apex:page standardController="Account">
<c:ContactComponent accId="{!Account.Id}"/>
</apex:page>

Visualforce Component:- (ContactComponent)

<apex:component controller="ContactController">
<apex:attribute name="accId" type="String" description="passing account Id" 
assignTo="{!assignedAccId}"/>
<apex:pageBlock title="Contact Information">
      <apex:repeat value="{!contactRecords}" var="c">
         Contact Name: {!c.Name}<br/>
      </apex:repeat>
    </apex:pageBlock>
</apex:component>

Apex Controller:- (ContactController)

 
public class ContactController {
  
  //Get AccountId value from Component's Attribute named AccId
  public Id assignedAccId {get;set;}  
  
  //Why are we using a getter method getContactRecords instead of a Getter Setter variable here?
  //If we ever try to use ContactRecords as a getter setter variable, then we have to intantiate the variable inside the constructor.
  //Getter Setter always runs after the constructor. Hence the assignedAccId will not be available while the constructor runs.  
  //Getter Setter method automatically runs when it is referenced on the page, and that referenced getter method is executed during the page load.
  
  //Return contacts for given AccountId.   
  public List<Contact> getContactRecords(){
     return [Select Id, Name From Contact Where AccountId=:assignedAccId]; 
     
  }    
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s