Category: Salesforce

2.1 When standardcontroller is not sufficient

The Concept

Standardcontroller is awesome. However, in most cases, standard controller won’t be sufficient to cover our requirement. Think about the following situations:

When you need to bring up and fill in multiple object’s data. When you want to retrieve a list of records and bring them to the front page. When the user input data needs to be handled before they can actually be stored.

And many, many more.

Actually, if Visualforce can only work with standardcontroller, it won’t be that powerful at all.

Some Code to Demonstrate

Let’s create a page which displays Merchandise information at the top and user and create a transaction for that merchandise at the bottom.

Assuming you have created the Merchandise, Transaction and Customer SObjects. The details of Transaction and Customer SObject are at here.

Let’s create an Apex code controller called AddTransactionController with the following code:

public class AddTransactionController { public Merchandise__c curMer {get; set;} public Transaction__c curTrans {get; set;} public AddTransactionController(ApexPages.StandardController con) { String curMerId = con.getId(); curMer = [Select Id, Name, Original_Price__c, Discount_Type__c, Discounted_Price__c From Merchandise__c Where Id = :curMerId]; curTrans = new Transaction__c(); } public pageReference AddTransaction() { curTrans.Merchandise__c = curMer.Id; insert curTrans; PageReference pr = new PageReference(‘/’ + curTrans.Id); return pr; } }

And a Visualforce page called AddTransaction with the following code:

<apex:page standardController=”Merchandise__c” extensions=”AddTransactionController”> <apex:sectionHeader title=”Merchandise” subtitle=”Choose List”/> <apex:form > <apex:pageBlock title=”Merchandise”> <apex:pageBlockButtons > <apex:commandButton action=”{!AddTransaction}” value=”Add Transaction”/> <apex:commandButton action=”{!cancel}” value=”Cancel” immediate=”true”/> </apex:pageBlockButtons> <apex:pageBlockSection title=”Merchandise Info”> <apex:outputField value=”{!curMer.Name}”/> <apex:outputField value=”{!curMer.Original_Price__c}”/> <apex:outputField value=”{!curMer.Discount_Type__c}”/> <apex:outputField value=”{!curMer.Discounted_Price__c}”/> </apex:pageBlockSection> <apex:pageBlockSection title=”New Transaction”> <apex:inputField value=”{!curTrans.Amount__c }”/> <apex:inputField value=”{!curTrans.Customer__c }”/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

Save it and give it a try with an existing merchandise Id. For me, my url looks like this:

Replace it with your org instance name and merchandise Id.

Try to understand the code, but don’t try too hard. It is a bit tricky for now. So I will take a whole post to explain in the next post.

Next Post

2.2 Use apex to talk to database and persist data