Thursday, 12 June 2014

Visualforce Markup and Controllers

A Visualforce page is comprised of two key elements:

1. Visualforce Markup
2. A Visualforce Controller

That means the page behaviour is a result of these two components. Visualforce is built on the MVC model. The markup is the VIEW part of the MVC model, whereas the controller is the CONTROLLER part of the MVC model. The MODEL is hidden behind, which is essentially the metadata repository. 

Visualforce Markup comprises of Visualforce tags, HTML, Javascript, Style components, any web-enabled code (for example : widgets), which are embedded within a single <apex:page> tag. The markup drives how the page should look like, when the page renders in a browser.

Visualforce Controllers are basically set of instructions created out of classes that may be standard or custom, that are responsible for driving how a page or rather to be precise, the page components, should behave when an event or action takes place on that page component. For example, if you are wondering what part of Visualforce takes care of the behavior of the application when a button click or a link click takes place, well, this is taken care by the controller.

There are two types of controllers - Standard Controller and Custom Controllers. A Standard Controller is a controller that is provided by the Force.com platform. On the other hand, a Custom Controller is basically a controller class written using the Apex language.

A Standard Controller comprises of logic and rules that are used in native Salesforce.com pages. For example, if we are using a standard Contacts controller and implementing the EDIT functionality, the same behavior is exhibited when EDIT action is being executed in the Salesforce.com Contacts page.  

And as obvious, if a Standard Controller is being used on a page where a user does not have privilege on that controller, a message is displayed that displays that the user does not have sufficient privileges over the controller. And such messages can ofcourse be avoided well in advance, by checking user's privileges on objects.

Whereas Standard Controllers act on single records, Standard List Controllers  act on multiple records. There are some examples of Salesforce.com pages that use Standard List Controllers such as:
1. List Pages
2. Related Lists
3. Mass action pages.

Now talking about Custom Controllers, these are basically classes that implement the entire logic of a page, without using Standard Controllers. However, some functionality of Standard Controllers are reimplemented.

System Mode vs. User Mode

It is interesting to know that Custom Controllers work in System Mode, which means that when Custom Controllers are used to render a Visualforce page, the object level permissions and field level permissions of the current user are ignored. However, it can be specified in the User's profile whether he/she can executed a method in a Custom Controller. This is a very powerful feature of a custom controller. Standard Controllers run in User Mode. This means that pages built on Standard Controllers will inherit the field level security plus the object level security of the user.

Now that we have discussed what are Standard Controllers and Custom Controllers, it is important to mention what Controller Extensions are. Well, Controller Extensions are nothing but classes built on Apex, that add to or override the functionalities of Standard or Custom controllers. This way, developers can make custom and standard controllers even more feature packed. Note that Controller Extensions run in System mode.

The optional modifier with sharing which allows the current user to get permissions even to pages that use Custom Controllers or Controller extensions.

Wednesday, 11 June 2014

Passing values between pages in Visualforce

There are different ways through which values can be passed between pages in Visualforce. I would like to talk about the two most common ways to transfer data between the Visualforce web pages.

Method 1. Passing variable value between two pages that implement the same controllers and extensions.
Method 2. Passing values using a Querystring.


Method 1


In order to use the first method above, we need to ensure that the two pages in context need to have the same controller. This might be a Standard controller or a Custom controller.


Say we have to pages Page1 and Page2. Let the Visualforce syntax be as below:


Code for Page1
<apex:page controller="customcontroller1">
   <apex:inputtext id="inpEmployeeName" value="{!EmployeeName}"/><br/>
   <apex:CommandButton value="Next" action="{!next}" id="cmdNext" />
</apex:page>


Code for Page2

<apex:page controller="customcontroller1">
   .The employee name is {!EmployeeName}
</apex:page>

Code for customcontroller1
public with sharing customcontroller1
{
  public string EmployeeName {get;set;} 
  
  // Function for navigating to next page
  public PageReference next()
  {
     PageReference nextpage = new PageReference('/apex/Page2');
     return nextpage;
  }
}

Now there are a few points worthy to note out here. You need to be careful of the method nextpage.setRedirect(true) , a method used to redirect from one page to another. Use it only when you use querystrings in the URL. If you use this method in the method above, it will wipe out all the data stored in variables in page1 being transferred to page2, as page2 in such a scenario will loose all the variable data of the controller, when this page2 loads.


Method 2

This method involves transferring variable data from one page to another, using a query string. This method should be used when the controller of the pages are different. See example below:

Say we have two pages, Page3 and Page4.

Code for Page3
<apex:page controller="customcontroller3">
   <apex:inputtext id="inpEmployeeName" value="{!EmployeeName}"/><br/>
   <apex:CommandButton value="Next" action="{!next}" id="cmdNext" />
</apex:page>

Code for Page4
<apex:page controller="customcontroller4">
   .The employee name is {!EmployeeName}
</apex:page>

Code for customcontroller3
public with sharing customcontroller3
{
  public string EmployeeName {get;set;} 

  // Function for navigating to next page
  public PageReference next()
  {
     PageReference nextpage = new PageReference('/apex/Page4?EN=' + EmployeeName);
     return nextpage.setRedirect(true); //Note that setRedect method is used here
  }
}


Code for customcontroller4
public with sharing customcontroller4
{
  public string EmployeeName {get;set;} 
  
  //Constructor
  public customcontroller4()
  {
    String strEmpName = ApexPages.currentPage().getParameters().get('EN');
  }
 }

This way, you can transfer data from a page to another even if they don't have the same controller. 


There is another way to transfer data between pages, and that is using Javascript and hidden fields in the form.

Tuesday, 29 April 2014

Callout from APEX Triggers

This tutorial shows how to make HTTP callout from an APEX trigger using Future method. 

Step 1: Create Apex Class

First step is to create an apex class. After you login, click on Setup > Develop > Apex Classes > New. 

Step 2: Write future method

Write future method that calls external service.
public class AccountUpdater {

  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateAccount(String id, String name) {

    //construct an HTTP request
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://cheenath.com/tutorial/sfdc/sample1/data.txt');
    req.setMethod('GET');

    //send the request
    Http http = new Http();
    HttpResponse res = http.send(req);

    //check the response
    if (res.getStatusCode() == 200) {

      //update account
      Account acc = new Account(Id=id);
      acc.Description = res.getBody();
      update acc;
    } else {
      System.debug('Callout failed: ' + res);
    } 
  }
}


Step 3: Add external server to Remote Sites

Click Setup > Security Controls > Remote Site Settings > New Add external site name and endpoint URL
Site:cheenath
endpoint url:http://cheenath.com/

Step 4: Create APEX trigger

Click Setup > Customize > Accounts > Triggers > New
And create the following trigger:
trigger descriptionUpdater on Account (after insert) {

  System.debug('Making future call to update account');
  for (Account acc : Trigger.New) {
    //Call future method to update account
    //with data from external server.
    //This is a async calls, it returns right away, after
    //enqueuing the request.

    AccountUpdater.updateAccount(acc.Id, acc.Name);
  }

}

Tuesday, 25 March 2014

Reserved Keywords in Salesforce

Total Number of  Reserved Keywords-130

    abstract
    global
    private
    activate*
    goto*
    protected
    and
    group*
    public
    any*
    having*
    retrieve*
    array
    hint*
    return
    as
    if
    returning*
    asc
    implements
    rollback
    autonomous*
    import*
    savepoint
    begin*
    inner*
    search*
    bigdecimal*
    insert
    select
    blob
    instanceof
    set
    break
    interface
    short*
    bulk
    into*
    sort
    by
    int
    stat*
    byte*
    join*
    super
    case*
    last_90_days
    switch*
    cast*
    last_month
    synchronized*
    catch
    last_n_days
    system
    char*
    last_week
    testmethod
    class
    like
    then*
    collect*
    limit
    this
    commit
    list
    this_month*
    const*
    long
    this_week
    continue
    loop*
    throw
    convertcurrency
    map
    today
    decimal
    merge
    tolabel
    default*
    new
    tomorrow
    delete
    next_90_days
    transaction*
    desc
    next_month
    trigger
    do
    next_n_days
    true
    else
    next_week
    try
    end*
    not
    type*
    enum
    null
    undelete
    exception
    nulls
    update
    exit*
    number*
    upsert
    export*
    object*
    using
    extends
    of*
    virtual
    false
    on
    webservice
    final
    or
    when*
    finally
    outer*
    where
    float*
    override
    while
    for
    package
    yesterday
    from
    parallel*

    future
    pragma*


Note:
               Keywords marked with an asterisk (*) are reserved for future use.

The following are special types of keywords that aren't reserved words and can be used as identifiers.
  • after
  • before
  • count
  • excludes
  • first
  • includes
  • last
  • order
  • sharing
  • with

Salesforce : APEX : Class ( Simple/Regular Vs Abstract Vs Virtual )

Note : simple/regular means, class without abstract and virtual keyword

Before going into differences between these, understand regular, abstract, virtual methods :
Regular Method  : Has code body or code implementation  and cannot be overridden

Virtual Method    : Has code body or code implementation and can be overridden by extending class method using override keyword

Abstract Method : Doesn't have body or code implementation and can be overridden by extending class method using override keyword



Regular Class:
a) Can be constructed ( can create object ).
b) Can not be extended
c) Can have regular methods
d) Can have virtual methods
e) Can not have abstract methods

Virtual Class:
a) Can be constructed ( can create object ).
b) Can be extended
c) Can have regular methods
d) Can have virtual methods
e) Can not have abstract methods

Abstract Class:
a) Can not be constructed ( can not create object ).
b) Can be extended
c) Can have regular methods
d) Can have virtual methods
e) Can have abstract methods

Note:
i) Extending class can not reduce visibility of super method by overriding it.
ii)Extending class can not change return type of super method by overriding it.
iii)Extending can do method over loading e.g.

Super class has 
public void getName(){
return 'My Name'; 
}

and Extending class can have
public getName(String str){
return str; 
}

iv) class can't extend two classes but can extend one class (virtual/abstract) and implements multiple interfaces.