Sunday, April 27, 2014

What is Aggregate Functions in SOQL?

What is  Aggregate Functions in SOQL?

Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. You can use aggregate functions without using a GROUP BY clause. For example, you could use the AVG() aggregate function to find the average Amount for all your opportunities.

AggregateResult[] groupedResults
  = [SELECT AVG(Amount)aver FROM Opportunity];
Object avgAmount = groupedResults[0].get('aver');

So the functions count(fieldname), count_distinct(), sum(), avg(), min() and max() return an AggregateResult object (if one row is returned from the query) or a List of AggregateResult objects (if multiple rows are returned from the query). You access values in the AggregateResult object much like a map calling a “get” method with the name of the column. In the example below you can see how you can access a column name (leadsource), alias (total) and an unnamed column (expr0). If you have multiple unnamed columns you reference in the order called with expr0, expr1, expr2, etc. 

List<aggregateResult> results = [select leadsource, count(name) total,
 count(state) from lead group by leadsource ]; 
for (AggregateResult ar : results)

The AggregateResult returns the value as an object. So for some operations you will need to cast they value to assign them appropriately.

Set<id> accountIds = new Set<id>();
for (AggregateResult results : [select accountId from contact group by accountId])

One this to be aware of is that the count() function does not return an AggregateResult object. The resulting query result size field returns the number of rows: 

Integer rows = [select count() from contact];
System.debug('rows: ' + rows);

You can also do some cool things like embed the SOQL right in your expression:

if ([select count() from contact where email = null] > 0) {
  // do some sort of processing...

Friday, April 25, 2014

What is Opportunity Contact Role?

What is Opportunity Contact Role?

Opportunity Contact Role represents the role of Contact/Person account on an Opportunity. There is many-to-many relationship between Opportunity and Contact, through a junction object  alled OpportunityContactRole. In an opportunity, you may add many opportunity contact roles. There is no restriction on Account from which the Contact can come, you can add any Contact from any Account. For example, Srinivas Balle might be the Executive sponsor for the opportunity “Universal Container”, and Edna Frank  might be the Quality Control for same Opportunity.

How to define Contact Role ?
According to your business requirement you can modify contact role for Opportunity.
To define contact role for Opportunity follow the steps Name > Setup > App Setup > Customize > Opportunities > Contact Role

If you want to add new role click on “New” Button, for reorder or make some value default click on “Reorder” button and save it.
Contact Role fields?
Below are the list of contact role standard fields, which Salesforce does not allow us to add any new custom field on Opportunity Contact Role.

How to add contact as a Contact Role inside Any Opportunity?

First choose the Opportunity in which you want to add Contact Role, then go to “Contact Role” related list click on “New” button.

Select Contact and its Role for particular Opportunity. You can make any contact as primary.

And Click on Save. You can add same contact as many times in Contact role for same opportunity.
Note: - There is certain restriction on this object unlike other system objects
  • We can’t add any custom fields into OpportunityContactRole Object.
  • We can’t add any validation rules on OpportunityContactRole object.
  • We can’t create any trigger on this OpportunityContactRole Object.
To implement above scenario we have to use Apex Schedule class and Inline VF page concept. I will explain these concepts in my next blog.

Thursday, April 24, 2014

How to get Maps from SOQL Query in salesforce?

How to get Maps from SOQL Query in salesforce?

As we all know, Apex code has limitation of  Number of code statements that can be executed. While writing Apex code, we should take care of number of code statement that are  executed to avoid governor limits. It is useful to understand how to reduce the number of executed code statements so that we can stay within the governor limits.

Normally we get list of records in a SOQL query.Sometime we also need set of id’s or map of record id’s and record or list of record id’s.

Apes code for above requirement will be as below:

//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;

//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;

//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>();

//Fetching all accounts
List<account> accList = [select Id,name,site,rating,AccountNumber from account limit 50000] ;

//Fetching Account ids
for(Account acc : accList){

In the code above, if there are large number of records(say 50000) then for loop will be executed 50000  times and also every line in for loop will be executed 50000 times. We can avoid this unnecessary for loop by using good SOQL query which will return map instead of list. After that we can easily get list of accounts or set of account Id’s or List of account Id’s using methods.

New Apex Code will be as below:

//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;

//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;

//Fetching all accounts
List<account> accList = new List<Account>();

//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>([select Id,name,site,rating,AccountNumber from account limit 50000]);

//getting list of account using map.values method
accList = accountIdObjMap.values();

//getting set of account Id's using map.keySet method
accIdsSet = accountIdObjMap.keySet();

//getting list of account Id's using list.addAll method

Tuesday, April 22, 2014

What are the Standard List Controller Actions?

What are the Standard List Controller Actions?

Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

• <apex:commandButton> creates a button that calls an action

• <apex:commandLink> creates a link that calls an action

• <apex:actionPoller> periodically calls an action

• <apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component,
call an action

• <apex:actionFunction> defines a new JavaScript function that calls an action

• <apex:page> calls an action when the page is loaded

The following table describes the action methods that are supported by all standard list controllers. You can associate these actions with any Visualforce component that includes an action attribute.

Inserts new records or updates existing records that have been changed. After this operation is finished, the save action returns the user to the original page, if known, or the home page.
Inserts new records or updates existing records that have been changed. Unlike the save action, quicksave does not redirect the user to another page.
Returns a PageReference object of the standard list page, based on the most recently used list filter for that object when the filterId is not specified by the user.
Aborts an edit operation. After this operation is finished, the cancel action returns the user to the page where the user originally invoked the edit.
Displays the first page of records in the set.
Displays the last page of records in the set.
Displays the next page of records in the set.
Displays the previous page of records in the set.

In the following example, the user specifies a filter for viewing account records. When the user clicks Go, the standard list page displays, using the selected filter.

<apex:page standardController="Account" recordSetVar="accounts">
<apex:selectList value="{!filterid}" size="1">
<apex:selectOptions value="{!listviewoptions}"/>
<apex:commandButton value="Go" action="{!list}"/>

Monday, April 21, 2014

What is Standard List controller in Salesforce?

What is Standard List controller in Salesforce?


What is Standard List controller in Visuaforce?

Standard list controllers allow you to create Visualforce pages that can display or act on a set of records. Examples of  work with a set of records include list pages, related lists, and mass action pages. Standard list controllers can be used with the following objects:

• Account

• Asset
• Campaign
• Case
• Contact
• Contract
• Idea
• Lead
• Opportunity
• Order
• Product2
• Solution
• User
• Custom objects

For example, to associate a page with the standard list controller for accounts, use the following markup:

<apex:page standardController="Account" recordSetVar="accounts">

The recordSetVar attribute not only indicates that the page uses a list controller, it can indicates the variable name of the record collection. This variable can be used to access data in the record collection

Accessing Data with List Controllers

<apex:page standardController="Account" recordSetVar="accounts" tabstyle="account"
<apex:pageBlock >
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:column value="{!}"/>

This results in a page that lists all the account names in your organization:

That's it !!!..

Sunday, April 20, 2014

Checking for Object Accessibility in Visualforce page.

Checking for Object Accessibility in Visualforce page.

If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible. To avoid this error, you should ensure that your Visualforce components will only render if a user has access to the object associated with the controller.

You can check for the accessibility of an object like this:

This expression returns a true or false value.
For example, to check if you have access to the standard Lead object, use the following code:

For custom objects, the code is similar:

where MyCustomObject__c is the name of your custom object.

<apex:page standardController="Lead">
<apex:pageBlock rendered="{!$ObjectType.Lead.accessible}">
<p>This text will display if you can see the Lead object.</p>
<apex:pageBlock rendered="NOT({!$ObjectType.Lead.accessible})">
<p>Sorry, but you cannot see the data because you do not have access to the Lead object.</p>

Thast it !!!!!

Saturday, April 19, 2014

How to Render data into MS-Execl using Visualforce?

How to Render data into MS-Execl using Visualforce?

Here i am sending particular account related contact detail to MS-Execl, for this you need mention content-type attribute in <apex:page> tag.

Here is the Example.

<apex:page standardController="Account" sidebar="false" contentType="application/" cache="true">
  <apex:pageBlock title="Hello {!$User.FirstName}!">
      You are viewing the {!} account.
   <apex:pageBlock title="Contacts">
      <apex:pageBlockTable value="{!account.Contacts}" var="contact">
         <apex:column value="{!contact.Name}"/>
         <apex:column value="{!contact.Email}"/>
         <apex:column value="{!contact.Phone}"/>

in content-type attribute i have mentioned the format as MS-Excel and name of the file as "sfdcsrini_Excel". You have to set cache="true" for IE support.

Finally you need to pass the particular account id in to url

Friday, April 18, 2014

How to Generate MS-Word document using VF pages?

How to Generate MS-Word document using VF pages?

I have a VF which renders as MS-Word. for this you need to mention content type in <apex:page> tag. 


<apex:page standardController="Account"  contentType="application/msword#sfdcsrini.doc" cache="true">

<html xmlns:w="urn:schemas-microsoft-com:office:word">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<apex:outputText title="Welcome to word" value="{!$User.FirstName}"/>
<apex:pageBlock >
<div style="text-align:left" >
<b>Account Name :</b><apex:outputText value="{!}"/><br/>
<b>Account Number: </b><apex:outputText value="{!account.AccountNumber}"/><br/>


once you save this code in to your vf page you need to pass the account id in to url like

 here contentType="application/msword#sfdcsrini.doc" tells that page should render as ms-word document.(sfdcsrini) is the name of the document in content type, you can give your own name. 

Creating Word Templates for Conga Composer

Creating Word Templates in Conga Composer

Thursday, April 17, 2014

How to Read CSV file from Apex?

How to Read CSV file from Apex display in visualforce?

I recently had to develop a Visualforce page that allowed a Salesforce user to upload a CSV file and then generate some records from the parsed values. Yes, I know that is what the Data Loader is for, but the intended user here was not technically adept. And I thought it was an interesting experiment.

Visualforce page: csvuploadVF

<apex:page sidebar="false" controller="FileUploader">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Accounts.</b> </font>
      <apex:pageblocktable value="{!uploadedAccounts}" var="acc" rendered="{!NOT(ISNULL(uploadedAccounts))}">
          <apex:column headerValue="Account Name">
              <apex:outputField value="{!acc.Name}"/>
          <apex:column headerValue="Shipping Street">
              <apex:outputField value="{!acc.ShippingStreet}"/>
          <apex:column headerValue="Shipping City">
              <apex:outputField value="{!acc.ShippingCity}"/>
          <apex:column headerValue="Shipping State">
              <apex:outputField value="{!acc.ShippingState}"/>
          <apex:column headerValue="Shipping Postal Code">
              <apex:outputField value="{!acc.ShippingPostalCode}"/>
          <apex:column headerValue="Shipping Country">
              <apex:outputField value="{!acc.ShippingCountry}"/>


Apex Class:

public class FileUploader 

    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Account> accstoupload;
    public Pagereference ReadFile()
        filelines = nameFile.split('\n');
        accstoupload = new List<Account>();
        for (Integer i=1;i<filelines.size();i++)
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            Account a = new Account();
            a.Name = inputvalues[0];
            a.ShippingStreet = inputvalues[1];       
            a.ShippingCity = inputvalues[2];
            a.ShippingState = inputvalues[3];
            a.ShippingPostalCode = inputvalues[4];
            a.ShippingCountry = inputvalues[5];


        insert accstoupload;
        catch (Exception e)
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
        return null;
    public List<Account> getuploadedAccounts()
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
                return null;                    
            return null;


Finally then try to upload the sample file as below with CSV file format.

That's it !!!!!

Conga Composer Quick Start 3: Creating a Complete Conga Composer Solution

Conga Composer Quick Start 3: Creating a Complete Conga Composer Solution

Wednesday, April 16, 2014

Tuesday, April 15, 2014

Conga Composer Quick Start 1

Conga Composer Quick Start 1

Monday, April 14, 2014

What is Interaction Logs in salesforce?

What is Interaction Logs in salesforce?

An interaction log lets Salesforce console users write notes on records that appear on primary tabs. For example, when cases appear on primary tabs, an interaction log can appear so that users can take notes on cases. To display interaction logs, you must turn them on for page layouts assigned to different user profiles.

  1. Edit any page layout and click Layout Properties.
  2. Check Interaction Log and click OK.
  3. Click Save

Note: - If you turn interaction logs on or off, you must close and reopen records to see the changes.

| ,