Thursday, 30 August 2012

Creating a Simple Visualforce Page - Apex


In this lesson you’ll create a new, very simple Visualforce page, the equivalent of “Hello World.”
  1. In your browser, add the text /apex/Catalog to the URL for your Salesforce instance. For example, if your Salesforce instance ishttps://na1.salesforce.com, the new URL would be https://na1.salesforce.com/apex/Catalog.You’ll get an error message: Page Catalog does not exist.
    Visualforce 'Quick Fix' screen: Create page Catalog
  2. Click the Create Page Catalog link to create the new page. The Catalog page will be created with some default code.
  3. The Page Editor displays a preview of the new page above and the code below. It will look like this:
    Visualforce: New page with default code
    If the Page Editor is collapsed, click the Expand (Visualforce Page Editor expand button) button at the bottom right of your browser window.
  4. You don’t really want the heading of the page to say “Congratulations,” so change the contents of the <h1> tag to Product Catalog, and remove the comments and other plain text. The code for the page will now look something like this.
    <apex:page>
    
      <h1>Product Catalog</h1>
    
    </apex:page>
    You can add additional text and HTML between the tags, but Visualforce pages must begin with <apex:page> and end with</apex:page>.
  5. Click the Save button (Visualforce Page Editor save button) at the top of the Page Editor. The page reloads to reflect your changes.
Notice that the code for the page looks a lot like standard HTML. That’s because Visualforce pages combine HTML tags, such as <h1>, withVisualforce-specific tags, which start with <apex:>.

Enabling Visualforce Development Mode - Apex


The simplest way to get started with Visualforce is to enable development mode. Development mode embeds a Visualforce page editor in your browser. It allows you to see and edit your code, and preview the page at the same time. Development mode also adds an Apex editor for editing controllers and extensions.
  1. Click Your Name | Setup | My Personal Information | Personal Information.
  2. Click Edit.
  3. Select the Development Mode checkbox.
  4. Click Save.
After enabling development mode, all Visualforce pages display with the development mode footer at the bottom of the browser window.

Visualforce Pages with Apex Controllers


Visualforce is a component-based user interface framework for the Force.com platform. Visualforce allows you to build sophisticated user interfaces by providing a view framework that includes a tag-based markup language similar to HTML, a library of reusable components that can be extended, and an Apex-based controller model. Visualforce supports the Model-View-Controller (MVC) style of user interface design, and is highly flexible.
Visualforce includes standard controllers for every sObject available in your organization, which lets you create Visualforce pages that handle common features without writing any code beyond the Visualforce itself. For highly customized applications, Visualforce allows you to extend or replace the standard controller with your own Apex code. You can make Visualforce applications available only within your company, or publish them on the Web.
In this tutorial, you will use Visualforce to create a simple store front page. You’ll start with a simple product listing page that does not use Apex as a quick introduction to Visualforce. Then you’ll add a few features, like a simple shopping cart, to see how Visualforce connects to a controller written in Apex.

Retrieving a Record Using the Apex REST GET Method

In this lesson, you’ll use Workbench to send a REST client request to retrieve the new merchandise record you’ve just created in the previous lesson. This request invokes one of the Apex REST methods you’ve just implemented.
  1. In the REST Explorer, Click GET.
  2. In the relative URL box, append the ID of the record you copied from Lesson 2 of this tutorial to the end of the URL:/services/apexrest/Merchandise/.
  3. Click Execute. This causes the getMerchandiseById method to be called. The response returned contains the fields of the new merchandise record.

    Response returned by the REST GET method.
  4. Optionally, click Show Raw Response to view the entire response, including the HTTP headers and the response body in JSON format.

    Raw response returned by the REST GET request. 

Creating a Record Using the Apex REST POST Method

In this lesson, you’ll use REST Explorer in Workbench to send a REST client request to create a new merchandise record. This request invokes one of the Apex REST methods you’ve just implemented.
Workbench’s REST Explorer simulates a REST client. It uses the session of the logged-in user as an authentication mechanism for callingApex REST methods.
You might be able to skip the first few steps in this procedure if you already set up sample data with Workbench in a previous tutorial.
  1. Navigate to: workbench.developerforce.com.
  2. If prompted for your credentials, enter your login information and click Login.
  3. For Environment, select Production.
  4. Accept the terms of service and click Login with Salesforce.
  5. Click Allow to allow Workbench to access your information.
  6. After logging in, click utilities | REST Explorer.
  7. Click POST.
  8. The URL path that REST explorer accepts is relative to the instance URL of your org, so you only have to provide the path that is appended to the instance URL. In the relative URL box, replace the default URL with /services/apexrest/Merchandise/
  9. For the request body, insert the following JSON string representation of the object to insert:
    {
      "name" : "Eraser",
      "description" : "White eraser",
      "price" : 0.75,
      "inventory" : 1000
    }
    Note that the field names for the object to create must match and must have the same case as the names of the parameters of the method that will be called.
  10. Click Execute. This causes the createMerchandise method to be called. The response contains the ID of the new merchandise record.
  11. To obtain the ID value from the response, click Show Raw Response, and then copy the ID value, without the quotation marks, that is displayed at the bottom of the response. For example, "a04R00000007xX1IAI", but your value will be different. You’ll use this ID in the next lesson to retrieve the record you’ve just inserted.

Adding a Class as a REST Resource - Apex

Prerequisites:
  • Tutorial #1: Creating Warehouse Custom Objects
  • Tutorial #2: Using the Developer Console
  • Tutorial #8: sObjects and the Database
Let’s add a class with two methods and expose it through Apex REST.
  1. In the Developer Console, click the Repository tab.
  2. In the Setup Entity Type section, click Classes, and then click New.
  3. For the class name, enter MerchandiseManager and click OK.
  4. Delete the auto-generated code and add the following.
    @RestResource(urlMapping='/Merchandise/*')
    global with sharing class MerchandiseManager {
      
        @HttpGet
        global static Merchandise__c getMerchandiseById() {
            RestRequest req = RestContext.request;        
            String merchId = req.requestURI.substring(
                                      req.requestURI.lastIndexOf('/')+1);
            Merchandise__c result = 
                           [SELECT Name,Description__c,Price__c,Total_Inventory__c
                            FROM Merchandise__c 
                            WHERE Id = :merchId];
            return result;
        }
      
        @HttpPost
        global static String createMerchandise(String name,
            String description, Decimal price, Double inventory) {
            Merchandise__c m = new Merchandise__c(
                Name=name,
                Description__c=description,
                Price__c=price,
                Total_Inventory__c=inventory);
            insert m;
            return m.Id;
        }
    }
  5. Click Save.

Tell Me More...

  • The class is global and defined with the @RestResource(urlMapping='/Invoice_Statement__c/*') annotation. Any Apexclass you want to expose as a REST API must be global and annotated with the @RestResource annotation. The parameter of the@RestResource annotation, urlMapping, is used to uniquely identify your resource and is relative to the base URLhttps://instance.salesforce.com/services/apexrest/. The base URL and the urlMapping value form the URI that the client sends in a REST request. In this case, the URL mapping contains the asterisk wildcard character, which means that the resource URI can contain any value after /Merchandise/. In Step 3 of this tutorial, we’ll be appending an ID value to the URI for the record to retrieve.
  • The class contains two global static methods defined with Apex REST annotations. All Apex REST methods must be global static.
  • The first class method, getMerchandiseById, is defined with the @HttpGet annotation.
    • The @HttpGet annotation exposes the method as a REST API that is called when an HTTP GET request is sent from the client.
    • This method returns the merchandise item that corresponds to the ID sent by the client in the request URI.
    • It obtains the request and request URI through the Apex static RestContext class.
    • It then parses the URI to find the value passed in after the last / character and performs a SOQL query to retrieve the merchandise record with this ID. Finally, it returns this record.
  • The second class method, createMerchandise, is defined with the @HttpPost annotation. This annotation exposes the method as a REST API and is called when an HTTP POST request is sent from the client. This method creates a merchandise record using the specified data sent by the client. It calls the insert DML operation to insert the new record in the database and returns the ID of the new merchandise record to the client.

Apex REST


You can create custom REST Web service APIs on top of the Force.com platform or Database.com by exposing your Apex classes as REST resources. Client applications can call the methods of your Apex classes using REST to run Apex code in the platform.
Apex REST supports both XML and JSON for resource formats sent in REST request and responses. By default, Apex REST uses JSON to represent resources.
For authentication, Apex REST supports OAuth 2.0 and the Salesforce session. This tutorial uses Workbench to simulate a REST client. Workbench uses the session of the logged-in user as an authentication mechanism for calling Apex REST methods.
Note
Workbench is a free, open source, community-supported tool (see the Help page in Workbench). Salesforce.com provides a hosted instance of Workbench for demonstration purposes only—salesforce.com recommends that you do not use this hosted instance of Workbench to access data in a production database. If you want to use Workbench for your production database, you can download, host, and configure it using your own resources.