Visualforce Custom Controllers and Extensions

Sharing is Caring

When we create Visualforce pages in Salesforce we have a few different ways that we can architect the code that will do any business logic that we need.

Standard Controllers

In general, the standard controller should be the preferred choice because it doesn’t require us to write code and doesn’t operate in system mode. This means that we can use it and have a lot less security concerns.

If something can’t be done in a standard controller we could potentially add a controller extension into the mix that does do that operation.

Custom Controllers

A custom controller should be used when required data cannot be accessed using the standard controller or when you need to interact with a few different objects.

For example, it’s not possible to access data two levels down from the object controller (only one level down or five levels up).

Big thing to keep in mind is that custom controllers operate in apex system mode which means there’s very little security being done. You can use the with sharing keywords though to improve the security a little bit.

Controller Extensions

Controller Extensions allow us to extend the functionality of a standard or custom controller. The standard or custom controller extension is passed as a parameter to the constructor of the extension class.

I like to use controller extensions to encourage code reuse – ie a “wizard” style set of pages can use the same controller but then implement whatever needs to be different in the extensions.

Keep in mind that controller extensions work like all other apex and run in “system mode” unless it uses the standard controller so you might need to implement a lot of apex security checks yourself. My blog post Enforcing Security in Salesforce Apex covers this pretty well.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.