Friday, December 21, 2012

Querying sObject Relationships in Apex Programming Language

In Force.com Platform, many objects are related to each other as a parent or child. We call this as parent-to-child and child-to-parent relationships. In our article about sObject, we learnt that sObject in Apex programming language represents an object in Force.com Platform. 

So, just like the objects in Force.com platform, sObject in Apex is also aware of relationships. Let us see this with few examples.

The object Contact is related to the object Account by child-to-parent relationship. Contact is child, Account is parent and relationship name is Account. See the following lines code where it retrieves the Contact sObject and at the same time obtains parent information as well.
   Contact c = [SELECT Id, Name, Account.Name FROM Contact WHERE FirstName='John' LIMIT 1];
   Account a = c.Account;
   System.debug (a.Name);
   System.debug (c.Account.Name);

When we are retrieving the Contact sObject into c, since we are reading Account.Name as part of the query, we are able to read c.Account as Account sObject. Hence able to read the parent account name. In Account.Name in the query, Account is the relationship name.

Now another scenario. The object Account is related to the object Contact by parent-to-child relationship. Account is Parent, Contact is child and relationship name is Contacts. See the following lines of code where it retrieves the Account sObject and at the same time retrieves all its Contacts as children.
   Account a = [SELECT Id, Name, (SELECT FirstName, LastName FROM Contacts) FROM Account WHERE Name='ABC Corp'];
   System.debug (a.Name);
   List <Contact> children = a.Contacts;
   System.debug('Number of contacts: ' + children.size());
   for (Contact c: children) {
   System.debug(c.FirstName);
   }


When we are retrieving the Account sObject into a, we are reading its children Contacts using a sub query. Hence able to extract all its children sObjects into an array and read them out as individual sObject.

Happy cloud computing using Salesforce!

Thursday, December 20, 2012

sObject in Apex Programming Language

In our article, Overview of Apex Programming Language, we learnt that Apex is data focused and programming in Apex is like writing stored procedures in a database. The very important element of the language which makes the integration with the database very easy to use is sObject. We briefly looked at it in our previous article, Data Types in Apex. Let us have a detailed look in this article.

sObject represents an Object in Force.com platform. We know that each object in Force.com platform, standard or customized, is just like a table in the database. sObject data type in Apex corresponds to these database objects. In other words, it is an object that can be stored in the Force.com platform database.


The following example creates an empty Account Object and assigns it to sObject. As you can see, it is just like instantiating a class.


    sObject s = new Account();
Instead of the generic sObject, you could instantiate it with specific type Account which is an sObject as well. 

    Account a = new Account();
You can instantiate the object with initial values or assign the value after instantiating it like below.

    Account a = new Account(Name='ABC Corp');
The above statement is same as the following 2 statements,

    Account a = new Account();
    a.Name = 'ABC Corp';

You can retrieve an sObject using Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL). You also use sObject while executing Data Manipulation Language (DML). We will sure explore all the three - SOQL, SOSL and DML in detail in future articles. 


The following example uses SOQL to retrieve an sObject -
    Account a = [SELECT Id, Name, Description FROM Account WHERE Name='ABC Corp'];
You can then read the individual field values using the dot notation like a.Id, a.Name or a.Description.

You can retrieve an array of sObject as below -

    Account[] a = [SELECT Id, Name, Description FROM Account]; 
Another specialty of sObject is using an sObject, you can get related parent and child sObjects and access their fields. We will explore this one as well in detail in one of our future articles.


Happy cloud computing using Salesforce!

Tuesday, December 18, 2012

Apex Trigger in Force.com

Apex Trigger in Force.com platform is a procedure written in Apex programming language that operates on an object at the defined events. The events could be before or after records are inserted, updated, or deleted in the database.

When the trigger is running, there could be several records meeting the criteria. For example, you have a trigger defined on object Account, at event before inserting. When the trigger is running there could be many Account records that are being inserted. Your trigger procedure runs on all these Accounts. As you can see since the trigger is fired when database records are manipulated, your trigger code is probably further manipulating the data that is being stored.

System.Trigger class provides all the information related to the trigger that is being fired. Within the Trigger procedure, using the instance of this class you can figure out the operation that triggered the event. Using the same System.Trigger class, you can also have access to the new data if insert/update trigger as well as the old data prior to the operation if it is update/delete trigger.

Triggers are defined on the objects. On object definition detail page, there is a section called Triggers. This is where you can add/manage triggers. Trigger code is compiled when it is saved and must compile successfully to be able to save.

Apex Trigger procedure syntax is -

trigger TriggerName on ObjectName (events) {

code_block

}

where events can be comma separated list of one or more of the following -
  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete
Any database changes made by trigger are automatically committed on successful completion of the trigger, otherwise changes are rolled back.

That is in brief about the Apex Trigger. You can understand the workings of this better by implementing some of the triggers.

Happy cloud computing using Salesforce!

Tuesday, December 11, 2012

Data Types in Apex Programming Language

Apex is a strongly typed, object-oriented programming language. Just like any other programming language, Apex has variety of data types that you can use. Let us see that list in this article.

Primitive Types - This data types include String, Integer, Long, Double, Decimal, ID, Boolean, Date, Datetime, Time and Blob. All these data type variables are always passed by value in methods.  Another point to note is in Apex, all variables are initialized to null when declared. You must explicitly initialize to non-null values before using.

sObject Types - This is a special data type in Apex. sObject is a generic data type for representing an Object that exists in Force.com. It could be Standard object like Account, Opportunity etc., or Custom object that you define.  Following are some of the examples of sObject variables -

    sObject s = new Account();
    Account a = new Account();
    CustomO__c c = new CustomO__c();

As you can see above, your custom objects have an extension of __c to distinguish from the Force.com standard objects. Fields from the sObject variable can be accessed using the dot notation. For example,
        
    a.Name = 'ABC Corp';

Collections - Apex has 3 types of collections. Lists, Sets and Maps.
  • A list is like an array, a sequential collection of elements with first index position as zero. List can contain elements of primitive types, sObjects, user-defined objects, Apex objects or even other collections. A list can contain up to four levels of nested collections. List can contain duplicate elements.
  • A set is also a collection of elements and elements can be of any data type. Unlike list, set contains unique elements and elements in set are not in any specific order. 
  • A map is a collection of key-value pairs. Keys and values can be any data type. Keys are unique and map elements must be accessed by the key as the order of  map elements are not reliable.
Enums - Just like in other programming languages, Enum type represents a fixed set of named constants. 

Apex variables can be objects created from user defined Apex classes or objects created from  system supplied Apex classes as well.

Happy cloud computing using Salesforce!

Friday, December 7, 2012

Overview of Force.com Apex Programming Language

We have been studying how one can build and customize applications using the Force.com Platform point and click method. A very powerful and sophisticated business application can be built using the platform and yes, just using the point and click method. But there are always times where your organization may have a requirement that the platform may not support. One way this custom functionality can be implemented is using the Force.com programming platform, Apex.

Just like everything else with Force.com, Apex which is part of the platform is fully controlled and hosted  by the platform. It runs in the cloud on Force.com servers.

Apex is a strongly typed, object oriented programming language. Code is compiled and stored as metadata. When executed by the end-user,  the Apex run time interpreter reads the compiled instructions from the metadata and returns the result.

Apex allows developers to add business logic to system events like button clicks and data updates. 

  • Apex can be invoked through the use of triggers. 
  • Apex classes can be scheduled to run at specific times.
  • Web service methods can be implemented in Apex and and can be invoked using Ajax Toolkit.
  • Apex code can be executed on the fly by executing it as anonymous block.

Apex language is very much data focused. It provides calls for data manipulation, querying and looping through the data but does not provide any support for rendering elements in the user interface. If you have any database development exposure, you can very much relate coding in Apex to writing database stored procedures.

Apex also supports test driven development process by allowing you to  create and execute unit tests. 

We will be exploring 'Programming in Apex' in detail in our future articles.

Happy cloud computing using Salesforce!

Chatter, the Salesforce Social Platform

The chatter from the Salesforce platform allows for easy collaboration and knowledge sharing between departments and employees in any organization using the applications built on Force.com platform. It helps  you to be on top of the latest happenings in your organization by connecting with people, following real time updates and sharing information securely.

Let us see some of the features of Chatter application.

Status Updates - You can share your status in real time. Your status update can include a file or a link as well. One who is following your feed can give feedback, comment and engage in a conversation. Status updates helps to keep everyone informed of various updates within the company.

Follow People, Documents and Data - Chatter allows for following not just people, you can follow documents and data as well. You can receive status updates on the progress of the document you are following. Updates on the data can be followed too. For example, you are interested in knowing how certain opportunities progress and when it closes. You can get those updates right in your chatter! 

Respond to Workflow Approvals - Workflow approvals are built and designed to achieve an effective  flow of business process. When it is your time to act upon to approve any step, you may do so right from your chatter feed.

Group Communication - You can form groups to communicate and share information better. You can have private groups with specific colleagues, or public groups or even customer based groups. Thus, you can have full control on what you want to share and with whom you want to share.

Security and Sharing - Chatter is all about so much of sharing and receiving updates. But there is always an underlying sharing model built into the Force.com platform which decides what you can see and act upon. The chatter fully supports this model and ensures that you can see only what you are allowed to see.

These are the overall features of chatter in Salesforce platform. Using the applications built on Force.com platform, you can monitor and act upon almost anything that matter most to you within an organization to work together in teams.

Happy cloud computing using Salesforce!

Approval Process in Force.com

In some of the recent articles we studied about Workflow and how to set them up in Force.com platform. The other part of workflow is Approval Process. Workflow is triggered when a record is added or updated. Approval process is triggered when the user manually clicks on 'Submit for Approval' button.

An approval process consists of steps and actions. An approval process is a sequence of steps that finally declare the record as approved. You can also define who must approve at each step. Thus, by defining approval process, records that need different approvals are submitted to the right people at the right time. And just like workflows, we can setup actions as part of the approval process as well. 

An approval process consists of the following -

1. Process Definition - Process definition contains Name and Description. Entry Criteria can be specified here for setting a filter to find the records for which you are applying the approval process. You can specify the user for automated approval routing for approval steps and also specify if the approver along with the administrator can edit records that are pending approval. Email template can be specified to use for notifying approvers. The approval page can be designed to display appropriate details for approver to see while approving. You can specify initially who can submit the records for approval.

2. Initial Submission Actions - You can specify actions to execute when a record is initially submitted for approval. Actions could be Task, Email Alert, Field Update or Outbound Message.

3. Approval Steps - You can define one or more approval steps in the approval process. Approval steps are numbered that determines the order. Entry criteria can be specified for each step allowing records to enter that step only if it meets the criteria. You can specify who should approve the records that are in this step. For each step you can specify approval and rejection actions.

4. Final Approval Actions - You can specify actions to execute at the end of the approval process, that is after the record has passed all the necessary steps and approved.

5. Final Rejection Actions - Just like final approval actions, you may specify rejection actions to indicate what must happen if rejected.

6. Recall Actions - An approval request can be recalled. Hence you could specify actions to execute if recalled.


As you can see, the Force.com platform lets us cover all the possibilities. As you can also imagine, how quickly an approval process can get too complicated, a through planning and designing is a must before we venture into setting up approval process.

Happy cloud computing using Salesforce!





Thursday, December 6, 2012

Creating Workflow Action for assigning a task in Force.com

One of the workflow actions that we can set up to execute in Force.com platform is 'Task Assignment'. Let us explore the steps involved in setting up this type of workflow action using Force.com platform.

From the App Setup -> Create -> Workflow & Approvals -> Tasks, you can create a new Task and use it while setting up workflow actions.

Otherwise, while setting up workflow actions you can click on 'New Task'. Both actions take you to the same page.

If you had come into this page via the 1st route mentioned above, you will need to select the object to which this task belongs to.  In the 2nd route, the object you have selected for the workflow rule is automatically selected for the action as well.

Enter task assignment information. This can be set to a 'User', 'Role', 'Owner' or 'Creator'. Select Status and Priority for the task. Enter the Subject or Title for the task.

Set the due date for the task. This can be set based on a date field of the record or simply set it to the rule trigger date.

You can also check the 'Notify Assignee' box to send out an email notification to the assigned user  when the task assignment is made.



Save your work. If you created a new task, go ahead and associate it with a workflow rule and you will have a workflow action for assigning a task.


Happy cloud computing using Salesforce!

Monday, December 3, 2012

Creating Workflow Action for updating a field in Force.com

One of the workflow actions that we can set up to execute in Force.com platform is 'Updating a Field'. Let us explore the steps involved in setting up this type of workflow action using Force.com platform.


From the App Setup -> Create -> Workflow & Approvals -> Field Updates, you can create new Field Update and use it while setting up workflow actions.

Otherwise, while setting up workflow actions you can click on 'New Field Update'. Both actions take you to the same page.


Enter Name for the Field Update you are setting up. If you had come into this page via the 1st route mentioned above, you will need to select the object to which this field update belongs to.  In the 2nd route, the object you have selected for the workflow rule is automatically selected for the action as well.

Field to Update need to be specified. Based on the data type of the field selected for update, you get different options for specifying new field value. 


  • If it is a nullable field type, you can specify a blank (null) value for the new field. 
  • You can use a formula to set the new value. For example Today() + 7 for a date field.
  • For Record Owners, you can choose the user for new assignment.
  • For a boolean (True/False) type of field, you can select True or False as new value.
  • Another type of field is 'Picklist' where possible values are predefined. If you are updating this type of field, you can set the value to one above or below the current choice or to a specific predefined value.

Re-evaluate Workflow Rules after Field Change checkbox allows you to re-evaluate all workflow rules on the object after the field value is updated and hence trigger any workflow rules if the criteria are met. 

Save your work. If you created a new field update, go ahead and associate it with a workflow rule and you will have a workflow action for updating a field.


Happy cloud computing using Salesforce!

Friday, November 30, 2012

Setting up global email address for your organization in Force.com

When you set up workflow to send out emails in Force.com platform, you can set the from address to a generic email address of the organization. For example, instead of your own email address you could use contact@yourcompany.com. 

To be able to set these standard email address as from email address, you first need to set it up using a feature called organization-wide address.

Go to Administration Setup -> Email Administration -> Organization-Wide Addresses. By clicking on the 'Add' button you can enter an email address. You can use this across all profiles or limit to only certain profiles to use as from address.

Once the email address is added, a verification email is sent to that email address. The verification email provides a link where you can go and verify the email address. Until the verification is done, platform keeps that email address in 'Verification Request Sent' status. Once the verification is done, status changes to 'Verified'.

You will be able to use any of the verified status organization-wide email addresses as from email address for email alerts.

Happy cloud computing using Salesforce!