Sunday, March 10, 2013

Working with Data in the Query Editor


Working with Data in the Query Editor

Use the Query Editor in the Developer Console to query data from your organization. View query results in a Query Results view. You can also create, update, and delete data in a Query Results view.


  1. Query Editor
  2. Query Results view
Use the Query Editor to:
The results of a query display in a Query Results view. Use a Query Results view to:

Monday, March 4, 2013

Classes, Interfaces and Properties:

Classes, Interfaces and Properties:

Apex is an object-oriented programming language and this tutorial examines its support for these all important objects or class
instances as they're sometimes called. Objects are created from classes—data structures that contains class methods, instance
methods, and data variables. Classes, in turn, can implement an interface, which is simply a set of methods. Use the Developer
Console to execute all of the examples in this tutorial.
Here is an overview of what this tutorial covers.
• Classes and Objects: Classes are templates from which you can create objects.
• Private Modifiers: The private modifier restricts access to a class, or a class method or member variable contained in a class,
so that they aren’t available to other classes.
• Static Variables, Constants and Methods: Static variables, constants, and methods don’t depend on an instance of a class
and can be accessed without creating an object from of a class.
• Interfaces: Interfaces are named sets of method signatures that don’t contain any implementation.
• Properties: Properties allow controlled read and write access to class member variables.

Chapter 2: Apex Language Fundamentals
Lesson 1: Defining Classes
Apex classes are similar to Java classes. A class is a template or blueprint from which objects are created. An object is an instance
of a class. For example, a Fridge class describes the state of a fridge and everything you can do with it. An instance of the
Fridge class is a specific refrigerator that can be purchased or sold.
An Apex class can contain variables and methods. Variables are used to specify the state of an object, such as the object's name
or type. Since these variables are associated with a class and are members of it, they are referred to as member variables. Methods
are used to control behavior, such as purchasing or selling an item.
Methods can also contain local variables that are declared inside the method and used only by the method. Whereas class
member variables define the attributes of an object, such as name or height, local variables in methods are used only by the
method and don’t describe the class.
Tutorial #4: Creating and Instantiating Classes in Chapter 1 of this workbook shows how to create a new class. Follow the
same procedure, and create the following class:
public class Fridge {
public String modelNumber;
public Integer numberInStock;
public void updateStock(Integer justSold) {
numberInStock = numberInStock - justSold;
}
}
You’ve just defined a new class called Fridge. The class has two member variables, modelNumber and numberInStock,
and one method, updateStock. The void type indicates that the updateStock method doesn’t return a value.
You can now declare variables of this new class type Fridge, and manipulate them. Execute the following in the Developer
Console:
Fridge myFridge = new Fridge();
myFridge.modelNumber = 'MX-O';
myFridge.numberInStock = 100;
myFridge.updateStock(20);
Fridge myOtherFridge = new Fridge();
myOtherFridge.modelNumber = 'MX-Y';
myOtherFridge.numberInStock = 50;
System.debug('myFridge.numberInStock=' + myFridge.numberInStock);
System.debug('myOtherFridge.numberInStock=' + myOtherFridge.numberInStock);
This creates a new instance of the Fridge class, called myFridge, which is an object. It sets the values of the variables in the
object, and then calls the updateStock method, passing in an argument of value 20. When this executes, the updateStock
instance method will subtract the argument from the numberInStock value. Next, it creates another instance of the Fridge
class and sets its stock number to 50. When it finally outputs the values, it displays 80 and 50.
Lesson 2: Private Modifiers
The class, class methods, and member variables were all declared using the public keyword until now. This is an access
modifier that ensures other Apex classes also have access to the class, methods, and variables. Sometimes, you might want to

Chapter 2: Apex Language Fundamentals
hide access for other Apex classes. This is when you declare the class, method, or member variable with the private access
modifier.
By declaring the member variables as private, you have control over which member variables can be read or written, and how
they’re manipulated by other classes. You can provide public methods to get and set the values of these private variables. These
getter and setter methods are called properties and are covered in more detail in Lesson 6: Property Syntax. Declare methods
as private when these methods are only to be called within the defining class and are helper methods. Helper methods don’t
represent the behavior of the class but are there to serve some utility purposes.
Note: By default, a method or variable is private and is visible only to the Apex code within the defining class. You
must explicitly specify a method or variable as public in order for it to be available to other classes.
Let’s modify our Fridge class to use private modifiers for the member variables.
1. Modify the Fridge class and change the modifier of both variables to private:
private String modelNumber;
private Integer numberInStock;
2. Click Quick Save.
3. Execute the following in the Developer Console:
Fridge myFridge = new Fridge();
myFridge.modelNumber = 'MX-EO';
You'll receive an error warning: Variable is not visible: modelNumber. The variable modelNumber is now
only accessible from within the class—a good practice.
4. To provide access to it, define a new public method that can be called to set its value and another to get its value. Add the
following inside the class body of Fridge.
public void setModelNumber(String theModelNumber) {
modelNumber = theModelNumber;
}
public String getModelNumber() {
return modelNumber;
}
5. Click Quick Save.
6. Execute the following:
Fridge myFridge = new Fridge();
myFridge.setModelNumber('MX-EO');
System.debug(myFridge.getModelNumber());
This will execute properly. The call to the setModelNumber method passes in a string which sets the modelNumber
value of the myFridge instance variable. The call to the getModelNumber method retrieves the model number, which
is passed to the System.debug system method for writing it to the debug output.
Lesson 3: Constructors
Apex provides a default constructor for each class you create. For example, you were able to create an instance of the Fridge
class by calling new Fridge(), even though you didn’t define the Fridge constructor yourself. However, the Fridge

Chapter 2: Apex Language Fundamentals
instance in this case has all its member variables set to null because all uninitialized variables in Apex are null. Sometimes
you might want to provide specific initial values, for example, number in stock should be 0 and the model number should be
a generic number. This is when you’ll want to write your own constructor. Also, it’s often useful to have a constructor that
takes parameters so you can initialize the member variables from the passed in argument values.
Try adding two constructors, one without parameters and one with parameters.
1. Add the following to your Fridge class:
public Fridge() {
modelNumber = 'XX-XX';
numberInStock = 0;
}
public Fridge(String theModelNumber, Integer theNumberInStock) {
modelNumber = theModelNumber;
numberInStock = theNumberInStock;
}
The constructor looks like a method, except it has the same name as the class itself, and no return value.
2. You can now create an instance and set the default values all at once using the second constructor you’ve added. Execute
the following:
Fridge myFridge = new Fridge('MX-EO', 100);
System.debug (myFridge.getModelNumber());
This will output 'MX-EO'. You'll often see classes with a variety of constructors that aid object creation.
Lesson 4: Static Variables, Constants, and Methods
The variables and methods you've created so far are instance methods and variables, which means you have to first create an
instance of the class to use the modelNumber and numberInStock variables. Each individual instance has its own copy of
instance variables, and the instance methods can access these variables. There are times when you need to have a member
variable whose value is available to all instances, for example, a stock threshold variable whose value is shared with all instances
of the Fridge class, and any update made by one instance will be visible to all other instances. This is when you need to create
a static variable. Static variables are associated with the class and not the instance and you can access them without instantiating
the class.
You can also define static methods which are associated with the class, not the instance. Typically, utility methods that don’t
depend on the state of an instance are good candidates for being static.
1. Modify the Fridge class by adding the following static variable:
public static Integer stockThreshold = 5;
2. Execute the following in the Developer Console:
System.debug ( Fridge.stockThreshold );
This will output 5. Note how you didn't have to create an instance of the Fridge class using the new operator. You just
accessed the variable on the class.

Chapter 2: Apex Language Fundamentals
3. You can also change the value of this static variable by accessing it through the class name.
// Modify the static stock threshold value
Fridge.stockThreshold = 4;
System.debug ( Fridge.stockThreshold );
This will write 4 to the output.
4. Sometimes you want to declare a variable as being a constant—something that won't change. You can use the final
keyword to do this in Apex; it indicates that the variable might be assigned to a value no more than once. Modify the static
variable you just declared to as follows:
public static final Integer STOCK_THRESHOLD = 5;
You can still output the value of the field, for example, Fridge.STOCK_THRESHOLD; will work, but you can now not
assign any other value to the field, for example, Fridge.STOCK_THRESHOLD = 3; won't work.
5. Let's define a static class method that prints out the values of a given object that gets passed in as an argument. This will
be a great help for debugging. Add a new method to the Fridge class:
public static void toDebug(Fridge aFridge) {
System.debug ('ModelNumber = ' + aFridge.modelNumber);
System.debug ('Number in Stock = ' + aFridge.numberInStock);
}
6. Test out this new method by calling it in the Developer Console and passing in a Fridge instance:
Fridge myFridge = new Fridge('MX-Y', 200);
Fridge.toDebug(myFridge);
This is the output you’ll get in the Developer Console.
You now have an easy way to dump any object you create to the Developer Console!
Lesson 5: Interfaces
An interface is a named set of method signatures (the return and parameter definitions), but without any implementation.
Interfaces provide a layer of abstraction to your code. They separate the specific implementation of a method from the
declaration for that method. This way, you can have different implementations of a method based on your specific application.
For example, a fridge is a type of kitchen appliance, and so is a toaster. Since every kitchen appliance has a model number, the
corresponding interface can have a getModelNumber method. However, the format of the model number is different for
different appliances. The Fridge class and the Toaster class can implement this method such that they return different
formats for the model number.
Interfaces can be handy—they specify a sort of contract. If any class implements an interface, you can be guaranteed that the
methods in the interface will appear in the class. Many different classes can implement the same interface.
Try it out by creating an interface that is implemented by the Fridge and Toaster classes.

Chapter 2: Apex Language Fundamentals
1. Create an interface in the same way that you create a class:
public interface KitchenUtility {
String getModelNumber();
}
2. Modify your Fridge class to implement this interface. Simply add the words in bold to the definition of the class on the
first line.
public class Fridge implements KitchenUtility {
3. Now define a new class called Toaster that also implements the KitchenUtility interface.
public class Toaster implements KitchenUtility {
private String modelNumber;
public String getModelNumber() {
return 'T' + modelNumber;
}
}
Because both the Toaster and Fridge classes implement the same interface, they will both have a getModelNumber
method. You can now treat any instance of Toaster or Fridge as a KitchenUtility.
4. The following example creates an instance of a Fridge and Toaster. It then creates an array of KitchenUtility
objects using these two objects and treating them as KitchenUtility instances.
Fridge f = new Fridge('MX', 200);
Toaster t = new Toaster();
KitchenUtility [] utilities = new KitchenUtility[] { f, t };
String model = utilities[0].getModelNumber();
System.debug(model);
Lesson 6: Property Syntax
In Lesson 2: Private Modifiers, you modified the variables to be private, ensuring that they can only be accessed through a
method. That's a common pattern when developing Apex classes, and there is a shorthand syntax that lets you define a variable
and code that should run when the variable is accessed or retrieved.
1. Add a new property, ecoRating, to the Fridge class by adding the following:
public Integer ecoRating {
get { return ecoRating; }
set { ecoRating = value; if (ecoRating < 0) ecoRating =0; }
}
Think of this as creating a variable ecoRating, as well as code that should run when the value is retrieved (the code in
the get block) and code that should run when the value is set (the code in the set block). An automatic variable named

Chapter 2: Apex Language Fundamentals
value is made available to you, so that you know what value is being set. In this case, the properties setter checks for
negative ecoRatings, and adjusts them to 0.
2. Execute the following code to see a negative rating is converted to 0.
Fridge myFridge = new Fridge('E', 10);
myFridge.ecoRating = -5; // calls the setter
System.debug (myFridge.ecoRating); // calls the getter
This will output 0.

Saturday, March 2, 2013

Using the Developer Console:


Using the Developer Console:
The Developer Console lets you execute Apex code statements. It also lets you execute Apex methods within an Apex class or object. In this you open the Developer Console, execute some basic Apex statements, and toggle a few log settings.
Lesson 1: Activating the Developer Console
After logging into your Salesforce environment, the screen displays the current application you’re using (in the diagram below,
it’s Warehouse), as well as your name.
1. Click your name, and then Developer Console.
The Developer Console opens in a separate window.
Note: If you don’t see the Developer Console option, you might not be using an appropriate type of Force.com
environment—see Before You Begin at the beginning of this workbook for more information.
2. If this is your first time opening the Developer Console, you can take a tour of the Developer Console features. Click Start
Tour and learn more about the Developer Console.
You can open the Developer Console at any time, and activate it again by following this lesson.
Lesson 2: Using the Developer Console to Execute Apex Code
The Developer Console can look overwhelming, but it’s just a collection of tools that help you work with code. In this lesson,
you’ll execute Apex code and view the results in a System Log view. The System Log view is the Developer Console tool you’ll
use most often.
1. Click in the Execute field at the top of the Developer Console.
2. In the Enter Apex Code window, enter the following text: System.debug( 'Hello World' );
3. Deselect Open Log and click Execute.

Chapter 1: Orientation

Every time you execute code, a log is created and listed in the Logs panel.
Double-click a log to open it in a System Log view. You can open multiple logs at a time to compare results.
System Log view is a context-sensitive execution viewer that shows the source of an operation, what triggered that operation,
and what occurred afterward. You can use this view to inspect debug logs that include database events, Apex processing,
workflow, and validation logic.
Within a System Log view, you’ll use the Execution Log panel a lot. It displays the stream of events that occur when code
executes. Even a single statement generates a lot of events. The System Log captures many event types: method entry and
exit, database and web service interactions, and resource limits. The event type USER_DEBUG, indicates the execution of a
System.debug() statement.
5
Chapter 1: Orientation
1. Click in the Execute field and enter the following code:
System.debug( 'Hello World' );
System.debug( System.now() );
System.debug( System.now() + 10 );
2. Check Open Log and click Execute.
3. In the Execution Log panel, click the Executable checkbox. This limits the display to only those items that represent
executed statements. For example, it filters out the cumulative limits.
4. To filter the list to show only USER_DEBUG events, enter: USER in the Filter field.
Note: The filter text is case sensitive.
Congratulations—you have successfully executed code on the Force.com platform and viewed the results! You’ll learn more
about the Developer Console tools in later tutorials.
6
Chapter 1: Orientation
Tell Me More...
Help Link in the Developer Console
To learn more about a particular aspect of the Developer Console, click the Help link in the Developer Console.
Anonymous Blocks
The Developer Console allows you to execute code statements on the fly. You can quickly evaluate the results in the
Logs panel. The code that you execute in the Developer Console is referred to as an anonymous block. Anonymous
blocks run as the current user and can fail to compile if the code violates the user's object- and field-level permissions.
Note that this not the case for Apex classes and triggers. You’ll learn more about the security context of classes and
triggers in the summary of Tutorial #7: Classes, Interfaces and Properties.
Summary
To execute Apex code and view the results of the execution, use the Developer Console. The detailed execution results include
not only the output generated by the code, but also events that occur along the execution path. Such events include the results
of calling another piece of code and interactions with the database.
Tutorial #3: Creating Sample Data
Prerequisites:
• Tutorial #1: Creating Warehouse Custom Objects
Some tutorials in this workbook assume you already have sample data in your database. To be able to execute the examples,
you first need to create some sample records.
Use the Developer Console to populate the sample objects you created in Tutorial 1.
1. Start the Developer Console, then click in the input field next to Execute to display the Enter Apex Code window.
2. If you installed the package in Tutorial 1, execute the following code:
ApexWorkbook.loadData();
If you manually created your schema, copy, paste, and execute the code from the following gist URL:
https://gist.github.com/1886593
3. Once the code executes, close the console.
Tutorial #4: Creating and Instantiating Classes
Apex is an object-oriented programming language, and much of the Apex you write will be contained in classes, sometimes
referred to as blueprints or templates for objects. In this tutorial you’ll create a simple class with two methods, and then execute
them from the Developer Console.
Lesson 1: Creating an Apex Class Using the Developer Console
To create a Apex classes in the Developer Console:
7
Chapter 1: Orientation
1. Click Your Name > Developer Console to open the Developer Console.
2. Click the Repository tab.
The Setup Entity Type panel lists the different items you can view and edit in the Developer Console.
3. Click Classes, and then click New.
4. Enter HelloWorld for the name of the new class and click OK.
5. A new empty HelloWorld class is created in the lower half of the Developer Console. Add a static method to the class
by adding the following text between the braces:
public static void sayYou() {
System.debug( 'You' );
}
6. Add an instance method by adding the following text just before the final closing brace:
public void sayMe() {
System.debug( 'Me' );
}
7. Click Save.
8
Chapter 1: Orientation
Tell Me More...
• You’ve created a class called HelloWorld with a static method sayYou() and an instance method sayMe(). Looking
at the definition of the methods, you’ll see that they call another class, System, invoking the method debug() on that
class, which will output strings.
• If you invoke the sayYou() method of your class, it invokes the debug() method of the System class, and you see the
output.
• The Developer Console validates your code in the background to ensure that the code is syntactically correct and compiles
successfully. Making mistakes is inevitable, such as typos in your code. If you make a mistake in your code, errors appear
in the Problems pane and an exclamation mark is added next to the pane heading: Problems!.
• Expand the Problems panel to see a list of errors. Clicking on an error takes you to the line of code where this error is
found. For example, the following shows the error that appears after you omit the closing parenthesis at the end of the
System.debug statement.
Re-add the closing parenthesis and notice that the error goes away.
Lesson 2: Calling a Class Method
Now that you’ve created the HelloWorld class, follow these steps to call its methods.
1. Execute the following code in the Developer Console to call the HelloWorld class's static method. (See Tutorial 2 if
you've forgotten how to do this). You might have to delete any existing code in the entry panel. Notice that to call a static
method, you don’t have to create an instance of the class.
HelloWorld.sayYou();
2. Open the resulting log.
3. Set the filters to show USER_DEBUG events. (Also covered in Tutorial 2). “You” appears in the log:
9
Chapter 1: Orientation
4. Now execute the following code to call the HelloWorld class's instance method. Notice that to call an instance method,
you first have to create an instance of the HelloWorld class.
HelloWorld hw = new HelloWorld();
hw.sayMe();
5. Open the resulting log and set the filters.
6. “Me” appears in the Details column. This code creates an instance of the HelloWorld class, and assigns it to a variable
called hw. It then calls the sayMe() method on that instance.
7. Clear the filters on both logs, and compare the two execution logs. The most obvious differences are related to creating
the HelloWorld instance and assigning it to the variable hw. Do you see any other differences?
Congratulations—you have now successfully created and executed new code on the Force.com platform!
Lesson 3: Creating an Apex Class Using the Salesforce User Interface
You can also create an Apex class in the Salesforce user interface.
1. Click Your Name > Setup > Develop > Apex Classes.
2. Click New.
3. In the editor pane, enter the following code:
public class MessageMaker {
}
4. Click Quick Save. You could have clicked Save instead, but that closes the class editor and returns you to the Apex Classes
list. Quick Save saves the Apex code, making it available to be executed, yet it also lets you continue editing—making it
easier to add to and modify the code.
5. Add the following code to the class:
public static string helloMessage() {
return('You say "Goodbye," I say "Hello"');
}
10
Chapter 1: Orientation
6. Click Save.
You can also view the class you’ve just created in the Developer Console and edit it.
1. In the Developer Console, click the Repository tab.
2. In the Setup Entity Type panel, click Classes, and then double-click MessageMaker from the Entities panel.
The MessageMaker class displays in the source code editor. You can edit the code there by typing directly in the editor
and saving the class.
Summary
In this tutorial you learned how to create and list Apex classes. The classes and methods you create can be called from the
Developer Console, as well as from other classes and code that you write.
Tell Me More...
• Alternatively, you can use the Force.com IDE to create and execute Apex code. For more information, search for “Force.com
IDE” on the Developer Force site: http://developer.force.com/.