Create a Visualforce Page with Apex Controller in Salesforce

I work as a Salesforce developer in a company that uses Salesforce to manage its business. Our sales team creates business agreements with customers using the Contract object.

When a contract expires, the sales team needs to renew it to continue the agreement. Usually, users have to open the contract record and click the Renew button on the record detail page.

To make this process easier, we created a custom Visualforce page with Apex. This page displays the remaining days before the contract expires and changes the color of the number when the remaining days are less than 30.

Also, for each contract with less than 30 days remaining, there is a Renew Now button. This means the sales user does not need to open the record to renew the contract.

Instead, they can click the Renew Now button directly on the page, and the system will automatically create a new contract record with updated dates and status.

In this article, we will learn about how to create a visualforce page with Apex controller in Salesforce. In this, I will explain how to change the text color in a list and add a renew button for each record.

Create a Visualforce Page and Connect With Apex in Salesforce

Below, I will explain how to create a Visualforce page and connect it with Apex using a controller. This helps us build a custom page that we can customize according to our needs.

In Salesforce, when we want to renew a contract, we usually open the contract record first. If the contract has expired, then we renew it by clicking the renew button.

In the image below, you can see that there is no field to check the remaining days before the contract expires. Also, there is no Renew Contract button for each record.

Using Visualforce and Apex, we can create a custom page that shows contract details, like how many days are left before expiration, without creating a formula field on the object.

We can also add buttons like ‘Renew Now’ directly on the page, so users don’t need to open each contract record individually.

Renew Contract in Salesforce

Apex Class: Retrieve Data and Renew Contract in Salesforce

Now, let’s create the Apex class. For that, click the Gear icon -> Developer Console -> File -> New -> Apex Class.

After that, provide the class name. In this class, we will first define a list collection to store the contract records. To retrieve the records from the contract object, we will use the SOQL query. Here I fetched only Active contracts.

SELECT Id, ContractNumber, AccountId, Account.Name, StartDate, EndDate, ContractTerm, Status FROM Contract WHERE Status = 'Activated' ORDER BY EndDate ASC

Next, we will declare an Integer variable named daysRemaining. This variable will store the number of days left before the contract expires.

By using this variable in our Apex controller, we don’t need to create a formula field on the Contract object. The controller will calculate and display the remaining days dynamically.

Now, we need to renew the contract when the user clicks the Renew Now button. We will use a PageReference method called from the Visualforce page to handle this action.

To create a new contract record in Salesforce, we first create an instance of the Contract object. Then, we set the necessary field values by copying data from the old contract record, such as AccountId, Status, Contract Term, and contract dates.

After setting these values, we use a DML operation (insert) to save the new contract record in Salesforce.

This process creates a new contract based on the old one, but with updated information to continue the business agreement smoothly.

public with sharing class ContractRenewalController {
    
    public List<ContractWrapper> contractsList { get; set; }
    public Id selectedContractId { get; set; } 
    
    public ContractRenewalController() {
        contractsList = new List<ContractWrapper>();
        
        // Fetch active contracts
        List<Contract> contracts = [
            SELECT Id, ContractNumber, AccountId, Account.Name, StartDate, EndDate, ContractTerm, Status
            FROM Contract
            WHERE Status = 'Activated'
            ORDER BY EndDate ASC
        ];
        
       for (Contract c : contracts) {
               Integer daysRemaining;
                    if (c.EndDate != null) {
                        daysRemaining = Date.today().daysBetween(c.EndDate);
                   } else {
                               daysRemaining = null;
                     }
               contractsList.add(new ContractWrapper(c, daysRemaining));
          }
     }
    
    // Renew the contract
    public PageReference renewContract() {
        Contract oldContract = [
            SELECT Id, AccountId, StartDate, ContractTerm, Status, EndDate
            FROM Contract
            WHERE Id = :selectedContractId
            LIMIT 1
        ];
        
        // Create new contract record (renewal)
        Contract newContract = new Contract();
        newContract.AccountId = oldContract.AccountId;
        
        // Set new contract start date and term
        if (oldContract.EndDate != null) {
            newContract.StartDate = oldContract.EndDate.addDays(1); // Start the next day
        } else {
            newContract.StartDate = Date.today();
        }
        
        // Keep the same term or set default (e.g., 12 months)
        newContract.ContractTerm = (oldContract.ContractTerm != null) 
            ? oldContract.ContractTerm 
            : 12;
        
        newContract.Status = 'Draft'; // Default status
        insert newContract;
        
        ApexPages.addMessage(new ApexPages.Message(
            ApexPages.Severity.CONFIRM, 
            'New Contract created: ' + newContract.Id
        ));
        
        return null; // Stay on the same page
    }
    
    public class ContractWrapper {
        public Contract contract { get; set; }
        public Integer daysRemaining { get; set; }
        
        public ContractWrapper(Contract c, Integer daysRemaining) {
            this.contract = c;
            this.daysRemaining = daysRemaining;
        }
    }
}

Visualforce Page: Display User Interface (UI) in Salesforce

Below, we will create a Visualforce page that shows contract records, displays buttons like Renew Now, and applies colors or styles as per our requirements.

To create a VF page, click on File -> New -> Visualforce Page -> provide page name.

First, we need to define the controller that will provide the data and logic for the Visualforce page.

The controller fetches the contract records, calculates the remaining days, and handles the contract renewal action when the user clicks the Renew Now button.

We created an Apex class (ContractRenewalController), and its name needs to be passed as the controller in the Visualforce page. This way, the page can use the logic and data from that Apex class.

In the Visualforce page, we use the <apex:pageBlock title> tag to add a title to our page section. This title appears at the top and helps users understand what the page or section is about.

The <apex:pageBlockTable> tag is used to create a table in a Visualforce page. It displays a list of records in rows and columns. In this, we provided the {!contractsList} value, which we declared in the Apex class, and stored the active contracts with remaining days left before they expire.

Next, provide the column names for the table and specify the values to be displayed.

Next, we want to display the text in red for contracts with expiry days less than 30. For that, we use the style attribute with the IF condition:

style="{!IF(cw.daysRemaining <= 30, 'color:red;', '')}"

Again, we use an IF condition to show the Renew Now button only when the remaining days are less than 30. This way, the button displays only for contracts that need renewal soon.

<apex:page controller="ContractRenewalController">
    <apex:form id="frm">
        <apex:pageMessages />
        <apex:pageBlock title="Active Contracts for Renewal" id="pb">
            <apex:pageBlockTable value="{!contractsList}" var="cw">
                
                <apex:column value="{!cw.contract.ContractNumber}" headerValue="Contract Number"/>
                <apex:column value="{!cw.contract.Account.Name}" headerValue="Account"/>
                <apex:column value="{!cw.contract.StartDate}" headerValue="Start Date"/>
                <apex:column value="{!cw.contract.EndDate}" headerValue="End Date"/>
                
                <apex:column headerValue="Days Remaining">
                    <apex:outputText value="{!cw.daysRemaining}" 
                        style="{!IF(cw.daysRemaining <= 30, 'color:red;', '')}"/>
                </apex:column>
                
                <apex:column headerValue="Action">
                    <!-- Only show button when 30 or fewer days remaining -->
                    <apex:outputPanel rendered="{!cw.daysRemaining <= 30}">
                        <apex:commandButton value="Renew Now" action="{!renewContract}" rerender="pb">
                            <apex:param name="contractId" value="{!cw.contract.Id}" assignTo="{!selectedContractId}"/>
                        </apex:commandButton>
                    </apex:outputPanel>
                </apex:column>
                
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Proof of Concept:

After creating the Apex class and Visualforce page, you can see the table in the image below. It clearly shows the contract details.

For contracts that have expired or have less than 30 days left before expiry, the remaining days are shown in red. Also, the Renew Now button appears only for these contracts.

Now, let’s check what happens when we click the Renew Now button, whether it creates a new contract or not.

I will click the Renew Now button for the contract of Dickeson plc, and then we will check the Contract object to see if a new contract record has been created.

Create a Visualforce Page with Apex Controller in Salesforce

In the image below, you can see that we have two contracts for the same account.

One is the original contract, and the other is the new contract created after clicking the Renew Now button.

How to Renew Contract in Salesforce

Also, for the new contract, some values are filled in automatically as we set in the Apex class, while other values are copied from the old contract.

Activate Contract in Salesforce

In this way, we can create a visualforce page and connect with Apex in Salesforce.

Conclusion

I hope you have got an idea about how to create a Visualforce page and connect it with Apex in Salesforce. In this, I have explained how to build an Apex class to manage contract renewal and show contract details on the page.

The VF page shows how many days are left before a contract expires and highlights those with less than 30 days. It also has a “Renew Now” button that creates a new contract.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.