Menu Bar

Tuesday, 17 March 2015

Salesforce Contollers and Extension

In the context of visualforce, to take advantage of the built-in features of Visualforce to access your org's data, you must use a controller. All controllers are Apex classes, either standard Apex classes (ApexPages.StandardController or ApexPages.StandardSetController) or your own custom Apex class. You can also extend functionality of any of these with an Extension class.
I tend to be a bit picky with my terminology here. Controllers are controllers. Extensions are not controllers. And for me, the difference is that extensions cannot live by themselves on a page. In other words, I'm not permitted to use extensions, unless my page has a controller in the first place.
Another distinguishing feature is that a page is allowed only one controller ever. But I can add as many extensions as I need.
So let me begin (what has become a dissertation) with controllers:
Controllers are attached to your page using one of three mutually exclusive formats, standard controller, standard list/set controller, custom controller.
For a page with a single record, accessing standard data and behavior of your object you would use standard controller:
<apex:page standardController="Account"...> ... </apex:page>
If you want a page with many records, using standard list view, and list actions you could use standard list controller:
<apex:page standardController="Account" recordsetVar="accountsList"...> ... </apex:page>
If you want to use completely custom functionality and don't really need most of the standard object behaviors, custom controller is a good option, but bear in mind, any standard actions you want to use will have to be implemented in your custom class. A page with a custom controller would use the following attribute:
<apex:page controller="MyApexClass"...> ... </apex:page>
But bear in mind, you yourself can instantiate ApexPages.StandardController to use its features and functionality. I often use the pattern below to instantiate standard controller to get access to its methods:
public with sharing class MyApexClass {
  private ApexPages.StandardController ctrl;
  public Account acct {get;set;}
  public MyApexClass(){
    try{
      acct = [select Name from Account 
          where Id = : ApexPages.currentPage().getParameters().get('id')];
    } catch (QueryException e) {
      acct = new Account();
    }
      ctrl = new ApexPages.StandardController(acct);
  }
  public PageReference save(){
    //here I can put additional functionality or just leave it as-is.
    return ctrl.save();
  }
}
The above instantiates Standard Controller privately, but then surfaces a public save method that is just a pass-through of the controller's save method. The constructor does the housekeeping of creating the actual record I'm working with.
If I want to add to the functionality of any controller, I can then use an extension. Extensions work with either standard or custom controllers. Standard controller with custom extension, for me, is the most common construct I use for Visualforce that will operate inside my org. I get all the power of the standard controller, but all the flexibility of Apex. The syntax for an extension with a standard controller page would be as follows:
<apex:page standardController="account" extensions="MyExtClass"...> ... </apex:page>
The extension class is then required to implement a constructor that accepts the type of the controller. You will then typically want to get a handle to the standard controller instance that is floating around, and the sObject instance that it represents. So for a standard controller page:
public with sharing class MyExtClass {
  private ApexPages.StandardController ctrl;
  public Account acct {get;set;}
  public MyExtClass(ApexPages.StandardController controllerParam){
      ctrl = controllerParam;
      acct = (Account) ctrl.getRecord();
  }
  public PageReference customsave(){
    //here I override my standard save functionality before I return the save call.
    return ctrl.save();
  }
}
With a custom controller and extension, you can probably extrapolate from the above, but just to close the loop.
<apex:page controller="MyApexClass" extensions="MyExtClass"...> ... </apex:page>
Again, the extension class implements a constructor that accepts the type of the controller, only now it is my custom class. From there, apart from getting a local handle to your custom controller instance, there isn't a pattern, per-se, but the local handle allows you to interact directly with your custom controller, in whatever way necessary, of course. :
public with sharing class MyExtClass {
  private MyApexClass ctrl;
  public MyExtClass(MyApexClass controllerParam){
      ctrl = controllerParam;
  }
}
There are additional tricks that are very powerful, such as instantiating ApexPages.StandardSetController in your class to take advantage of that class' built-in paging, features. For more on that, there is a great video from Dreamforce 11 that shows how this can work:http://youtu.be/Js00YUpJAjs

28 comments:

Unknown said...

This blog having the details of Processes running. The way of runing is explained clearly. The content quality is really great. The full document is entirely amazing. Thank you very much for this blog.
Hadoop Training in Chennai

deeksha said...

this blog is very nice and effective thanks for sharing those information and for publishing valuable things.

php Training in Chennai

Anonymous said...


This blog explains the details of most popular technological details. This helps to learn about what are all the different method is there. And the working methods all of that are explained here. Informative blog.
Hadoop Training in Chennai

karthireva said...


wow great,nowadays this type of blog is more important and informative technology,it was more impressive to read ,which helps to design more in effective ways



SEO Training Institute in Chennai

Unknown said...


I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your

feed and I hope you post again soon.

Android App Development Company

Unknown said...

Hai Author, Very Good informative blog post,
Thanks

Ancy merina said...
This comment has been removed by the author.
Susmitha Bommepalli said...

Very nice information about. I would like to appreciate you. Keep it up!
Best Data Science Online Training Institute In Hyderabad | Online Data Science Training
Data Science Online Training Institute In Hyderabad
Data science online training in hyderabad
Best data science training in hyderabad



afiah b said...

Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
Oracle training in Chennai

Java training in Chennai | Java training in Annanagar

Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Unknown said...

Well somehow I got to read lots of articles on your blog. It’s amazing how interesting it is for me to visit you very often.
Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Java training in Bangalore | Java training institute in Bangalore | Java course in Bangalore

Java online training | Java Certification Online course-Gangboard

Java training in Pune

jeyanthi said...

Really you have done great job,There are may person searching about that now they will find enough resources by your post
Data Science Course in Indira nagar
Data Science Course in btm layout
Python course in Kalyan nagar
Data Science course in Indira nagar
Data Science Course in Marathahalli
Data Science Course in BTM Layout

sakthi said...

Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
microsoft azure training in bangalore
rpa training in bangalore
best rpa training in bangalore
rpa online training

tamilsasi said...


Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
Keep update more information..


Selenium training in bangalore
Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training
Selenium interview questions and answers

Quickbooks Expert said...

Nice Blog ! Our Quickbooks Desktop Payroll Support Number Expert will assist you in resolving the Quickbooks issues you are facing. Get connect with us for having instant solutions. We are available round the clock with the best solutions for you!

Praneeth M said...
This comment has been removed by the author.
Anonymous said...

С сумкой для девушек всё не так просто. Для женщины на первое место выходит то, как смотреться атрибут. Девушка принимает решение израсходовать некоторое время, чтобы пристраститься к исключительной для себя сумке в гардеробе, но при этом произвести первое впечатление на окружающих. В сумочке девушки можно найти документы, безделушки, сладости, освежитель для полости рта. Список может быть намного обширнее, всё упираеться от объема избранного атрибута. В гардеробе дамы одновременно несколько аксессуаров разных форм, расцветок и стилей. Для похода на работу или учёбу девушка выбирает большую сумку или клатч, для слеты с одногруппниками на закате. Интересно, что леди редко даруют сумку. Аксессуары дама избирает себе сама, а когда есть необходимость, то демонстрирует подругам то, что она хочет в атрибуте требующего подарка. Подарки и спонтанные приобретения здесь будут неуместны. Приобретение новой вещи – это важное событие, но черезмерно приятное. Поэтому осуществляйте это как можно чаще тут сумка без .

Anonymous said...

Dil Bechara 2020 FHD Download Here
Sushant Singh Rajput Last Movie Dil Bechara 2020 Download HDRip

Anonymous said...

Онлайн гадание пасьянс на ближайшее будущее это способ просмотреть приближающиеся явления постоянно завлекал людей. Хиромантия дозволяет предположить, что человека подстерегает в ближайшем времени. Каждый порывается предугадать собственное грядущее и считает определенные средства хиромантии гораздо больше результативными.

Anonymous said...

Подбирая хороший товар как например плитка настенная azulev необходимо просмотреть множественное число продуктов. Лучший выбор напольного покрытия может украсить всякую перегородку или санузел. Керамическая очень хорошо подойдет к любому интерьеру. Сосредоточьтесь не только на настенной плитке зарубежного изготовления, но и на наши разновидности.

Anonymous said...

Используя услуги рубль займ на карту, вы можете оперативно подобрать необходимые проценты по займу. Получайте кредит на карту для любых целей. Только ответственные кредиторы осуществляют свои действия на сайте Онлайн-займы.

Anonymous said...

Таролог в новосибирске является наиболее точным способом предсказать судьбу человека. Естественные катаклизмы или ритуальные убийства животных создали точное трактование обнаруженного. Первоначальные системы гадания образовались тысячи лет назад до нашей эры.

Anonymous said...

Яркое меню и стремительный поиск – это однозначный вариант найти интересную азартную игру. Колесо фортуны – наиболее трендовый слот средь интерактивных игрушек Казино Икс ком. Лишь на нашей платформе казино х гемблер имеет возможность нырнуть в увлекательные приключения.

Anonymous said...

Важно помнить, что играть в автоматы в казино х ни в коем случае не требует переводов за осуществление порядка регистрации игроков. Онлайн-поддержка всегда придет на помощь и мгновенно порешает наиболее сложную задачу. Посмотреть истинность портала возможно на официальной странице casino-x-oficialniy-sayt.com.

Anonymous said...

Развлекалово нынешнего поколения с огромными призами. Кибер Спорт – это новый период становления спортивных соревнований. Взглянув казино мистер бит на деньги вы попадете в немыслемый мир Компьютерных игр. Геймеры спорят в реакции, организуют реальные группы и побеждают в соревнованиях.

Anonymous said...

Гранитная крошка, как первичный компонент, не подвергается плавлению. При возникновении пожара мозаика ibero не испаряет опасных веществ. Серьезная стойкость обеспечивает долговечность материала на десятилетия.

Annus said...

Title:
Best Oracle DBA Training Institute in Chennai | Infycle Technologies

Description:
Set your career goal towards Oracle for a wealthy future with Infycle. Infycle Technologies is one of the best Oracle DBA training institute in Chennai, that gives the most trusted and best Oracle DBA Training with various stages of Oracle in a 100% hands-on training which will be guided by professional tutors in the field. In addition to this, the mock interviews will be given to the candidates, so that, they can face the interviews with full confidence. Apart from all, the candidates will be placed in the top MNC's with a great salary package. To get it all, call 7502633633 and make this happen for your happy life.
Best Oracle training in Chennai

Rajendra Cholan said...

Want to learn Big Data along with job opportunities? Infycle is with you to make your dream into reality. Infycle Technologies is the most trustworthy Big Data training institute in Chennai, which gives 100% hands-on practical training with professional tutors in the field. Along with that, the mock interviews will be assigned for the candidates, so that they can meet the job interviews with full confidence. To transform your career to the next level, call 7502633633 to Infycle Technologies and grab a free demo to know more

BEST TRAINING IN CHENNAI

Steven Cohen said...

Meta Fx Global. Now You Can Login Your Meta Fx Global E-Account Through Your Meta Fx Global Account Login.