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)
 System.debug(ar.get('leadsource')+'-'+ar.get('total')+'-'+ar.get('expr0')); 

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])
  accountIds.add((ID)results.get('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){
    accIdsSet.add(acc.id);
    accIdsList.add(acc.id);
    accountIdObjMap.put(acc.id,acc);
}



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
accIdsList.addAll(accIdsSet);





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.

Action
Description
save
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.
quicksave
Inserts new records or updates existing records that have been changed. Unlike the save action, quicksave does not redirect the user to another page.
list
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.
cancel
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.
first
Displays the first page of records in the set.
last
Displays the last page of records in the set.
next
Displays the next page of records in the set.
previous
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:form>
<apex:selectList value="{!filterid}" size="1">
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
<apex:commandButton value="Go" action="{!list}"/>
</apex:form>
</apex:page>

Monday, April 21, 2014

What is Standard List controller in Salesforce?

What is Standard List controller in Salesforce?

Or

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"
sidebar="false">
<apex:pageBlock >
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:column value="{!a.name}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>


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:
{!$ObjectType.objectname.accessible}

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:
{!$ObjectType.Lead.accessible}

For custom objects, the code is similar:
{!$ObjectType.MyCustomObject__c.accessible}

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>
<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>
</apex:pageBlock>
</apex:page>


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/vnd.ms-excel#sfdcsrini_Excel.xls" cache="true">
  
  <apex:pageBlock title="Hello {!$User.FirstName}!">
      You are viewing the {!account.name} account.
   </apex:pageBlock>
   <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}"/>
      </apex:pageBlockTable>
   </apex:pageBlock>
  
  
</apex:page>


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
like

https://c.ap1.visual.force.com/apex/msexcel?id=0019000000RMAaF


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. 

EX:-

<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"/>
<body>
<apex:outputText title="Welcome to word" value="{!$User.FirstName}"/>
<br/>
<br/>
<apex:pageBlock >
<div style="text-align:left" >
<b>Account Name :</b><apex:outputText value="{!account.name}"/><br/>
<b>Account Number: </b><apex:outputText value="{!account.AccountNumber}"/><br/>
</div>            
</apex:pageBlock>
</body>
</html>


</apex:page>


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

https://c.ap1.visual.force.com/apex/worddocvf?id=0019000000RMAaF


 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 >
             <center>
              <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>
             </center>  
      
      
      <apex:pageblocktable value="{!uploadedAccounts}" var="acc" rendered="{!NOT(ISNULL(uploadedAccounts))}">
          <apex:column headerValue="Account Name">
              <apex:outputField value="{!acc.Name}"/>
          </apex:column>
          <apex:column headerValue="Shipping Street">
              <apex:outputField value="{!acc.ShippingStreet}"/>
          </apex:column>
          <apex:column headerValue="Shipping City">
              <apex:outputField value="{!acc.ShippingCity}"/>
          </apex:column>
          <apex:column headerValue="Shipping State">
              <apex:outputField value="{!acc.ShippingState}"/>
          </apex:column>
          <apex:column headerValue="Shipping Postal Code">
              <apex:outputField value="{!acc.ShippingPostalCode}"/>
          </apex:column>
          <apex:column headerValue="Shipping Country">
              <apex:outputField value="{!acc.ShippingCountry}"/>
          </apex:column>
      </apex:pageblocktable> 
      
      </apex:pageBlock>       
   </apex:form>   

</apex:page>


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()
    {
        nameFile=contentFile.toString();
        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];

            accstoupload.add(a);

        }
        try{
        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');
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
    
    public List<Account> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
            else
                return null;                    
        else
            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.


 
| ,