Similar to standard Visualforce pages, custom components can be associated with a controller written in Apex. This association is made by setting the controller attribute on the component to your custom controller. You can use the controller to perform additional logic before returning the component's markup to the associated page.
Accessing Custom Component Attributes in a Controller
To access the value of a custom component attribute in an associated custom component controller:
-
Define a property in the custom component controller to store the value of the attribute.
-
Define a getter and setter method for the property. For example:
<!-- otherprops: apex_code set_clipboard -->public class myComponentController { public String controllerValue; public void setControllerValue (String s) { controllerValue = s.toUpperCase(); } public String getControllerValue() { return controllerValue; } }Notice that the setter modifies the value.
-
In the
<!-- otherprops: apex_page set_clipboard --><apex:attribute>tag in your component definition, use theassignToattribute to bind the attribute to the class variable you just defined. For example:<apex:component controller="myComponentController"> <apex:attribute name="componentValue" description="Attribute on the component." type="String" required="required" assignTo="{!controllerValue}"/> <apex:pageBlock title="My Custom Component"> <p> <code>componentValue</code> is "{!componentValue}" <br/> <code>controllerValue</code> is "{!controllerValue}" </p> </apex:pageBlock> Notice that the controllerValue has been upper cased using an Apex method. </apex:component>Note that when using the
assignToattribute, getter and setter methods, or a property withgetandsetvalues, must be defined. -
Add the component to a page. For example,
<!-- otherprops: set_clipboard --><apex:page> <c:simpleComponent componentValue="Hi there, {!$User.FirstName}"/> </apex:page>
The output of the page will look something like the following:

Notice that the Apex controller method changes controllerValue so that it is displayed with uppercase characters.