Monday 16 December 2013

Inline Editing is not available for a specific object

Inline editing is a handy bit of user friendliness,less time consuming and an efficient way of editing a value of a field from the detail page of a record OR from List View of records . Enabling inline editing is simple. We can enable from User Interface settings.
Here an image where you can enable inline editing. 
Go to the Set up-->Customize-->User Interface-- check Enable Inline Editing check box.




Now inline editing concept will not work for some object. Why is it not working for some object ?
To  use inline editing concept then edit action of specific object should not overridden with any visual-force page. If the Edit action has been overridden for an object, Inline Editing will not be available for that object.

To determine this:
For standard objects: Go to Setup | Customize | <Object> | Buttons & Links, and note the "Overridden" checkbox next to the 'Edit' standard button.

For custom objects: Go to Setup | Create | Objects | <Object>, scroll down to the Buttons & links section, and note the "Overridden" checkbox next to the 'Edit' standard button.

Thursday 12 December 2013

How to get Picklist Value of an object Dynamically

This is very simple. I am sharing some code ,please go through this
Here is My Controller 
public class testclass {
    public Job__c job{get;set;}
    public List<SelectOption> options{get;set;}
    public testclass(){
        options = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult = Job__c.Status__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry f : ple){
       
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }
    }
   
   
}

My Page 
<apex:page controller="testclass ">
  <apex:form>
      <apex:pageBlock>
          
          Order Status:<apex:selectList id="countries" value="{!job.Status__c}" size="1" required="true" >
              <apex:selectOptions value="{!options}"/>
          </apex:selectList>
      </apex:pageBlock>
      
  </apex:form>
  
</apex:page>

Wednesday 11 December 2013

Sending Custom Object Information in a Mail

Sometimes we try to send some custom object information in mail. For sending mail Sales-force has provided 4 types of email template. We can design the template as per our requirement. We can use simple text template and use merge field to send custom object information. But that template will work perfectly only If we use in the workflow. 
If we send mail from apex code then that merge field value will not be displayed, except we can display Lead ,Contact and User object information.

For example 

Dear {!Contact.Name} -- It will display

Sub-- {!CustomObject.name}-- It will not display.

This functionality is not yet activated by Sales-force, Here is an idea regarding same.

https://success.salesforce.com/ideaView?id=08730000000BpYU

Why not CustomObject information ?

If we use the template in apex code (By using Messaging.SingleEmailmessage method) for sending mail then setTargetObjectId(ID) method is required , Here we can only give id of USER,CONTACT and LEAD.

For example 
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;
mail.setTemplateId(some template id);
mail.setTargetObjectId(ID);
That 's the reason custom object merge field value will not be displayed in mail.

Solutions
Instead using the Sales-force Email template, design an template in apex code (using some HTMLtags depending according to your design).
Just make a query which information you want to send and then pass these value as parameter to a method.
List<CustomObject__c> listofCustomObjects = [SELECT id, Name,.Expiration__c ,Account_Name__c 
                                                                         FROM CustomObject__c]
 for(CustomObject__c license:listofCustomObjects ) {
            
            Integer numberDaysDue = System.Today().daysBetween(license.Expiration__c);
            String name = license.Account_Name__c;
            if(numberDaysDue == 30){
               
                sendingmail(numberDaysDue ,name );
            }  

}

public void sendingmail( Integer noOfdays, String accountName){
         
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;
         String[] toAddresses = new String[] {'jewell@test.com','neha.v@test.com','sexyRadha@test.com'};
         mail.setToAddresses(toAddresses) ;
         mail.setSubject('LMO:'+'  '+accountName+'  '+'licency expiry in'+' '+noOfdays+' '+'days');
        
         String body = '<html lang="ja"><body>'+ 
                          '<br><br>'+'This email alert is to bring to your notice that the licence of the client :'+'  '+'<b>'+accountName+'</b>'+'  '+'is going to expiry within'+'<b>'+' '+noOfdays+' '+'</b>'+
                          '<br><br>'+'From LMO Alert Service'+'</body></html>';
         mail.setHtmlBody(body);
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        

      }


Friday 6 December 2013

Salesforce Winter 14 – New Features



  • Apex statement  Governor limit is removed
  • Code coverage cloumn is removed in list of apex class
  • OFFSET can be used in SubQuery 
  • New Database methods added Database.getUpdatedDatabase.getDeleted and Database.merge.
  • Preview button added in visual force page
  • New componet  <apex:input> added, type attribute is used in this  <apex:input> component.
  • LoadOnReady=”true”  attribute is added in <apex:includeScript> component .
  • Developer consol support java script css,xml and plain text.
  • Static Resource can be created from Developer consol.
  • Till now Lookup field can only search Name field however now we have option to “search All” Fields.
  • Report chart is added in detail page, maximum 2 chart  can be added.
  • Business process like work flow can be written on User Object.
  • Salesforce login page will be completely customizable.
  • Service Cloud Console” is renamed to “Salesforce Console for Service”.
  • Configuration Only” sandbox renamed to “Developer Pro”.
  • Agent Configuration” renamed to “Live Agent Configuration”







Wednesday 4 December 2013

How to use Date Time Variable in Dynamic Query

In some scenario you might have come across to fetch record with in some date time range. 
Here I am sharing some code for this. Suppose I am querying records from Minutes Object. There is two field Start_Time and End_Time present  in Minutes Object.
This is my page 

 <apex:inputField value="{!minute.Start_Time__c}" required="true" label="From Date"/>
 <apex:inputField value="{!minuteObj.End_Time__c}" required="true" label="To Date"/>
<apex:commandButton action="{!convertValidMinutesToUsage}" value="Process Minute's"/>

This is my controller 
public with sharing class ControllerValidMinutesToUsage {
     public Minute__c minute{get;set;}
     DateTime startDate;
     DateTime endDate;
     string query;

     public ControllerValidMinutesToUsage(){
            minute =  new Minute__c();
    }

    public void convertValidMinutesToUsage(){
       String sStartdate;
       String sEndDate;
       startDate = minute.Start_Time__c;
       sStartdate = startDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
       endDate = minuteObj.End_Time__c+1;
       sEndDate = endDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
       query = 'SELECT Start_Time__c ,End_Time__c, Is_Valid__c WHERE Is_Valid__c = false';
       query += ' AND Start_Time__c >='+sStartdate+' '+'AND Start_Time__c <='+sEndDate
       list<Minute__c> =  DateBase.query(query );
    }
}

Tuesday 3 December 2013

How to get key prefix of an Object in Salesforce.

We know there are two types of record-id are present in salesforce.

  • 15 digit -- Case Sensitive
  • 18 digit -- Case Insensitive
Only 3 digit of ids represent object type .


for example 

  • Account-- 001
  • Contact-- 003
  • Opportunities --006
  • Lead  --- 00Q
How will get these prefix dynamically, I mean by using apex code ?

Schema.DescribeSObjectResult r = CustomObject__c.sObjectType.getDescribe();
String keyPrefix = r.getKeyPrefix();
System.debug('Printing --'+keyPrefix );
It will print prefix of Custom Object id.

Monday 2 December 2013

NOT IN Keyword in Soql in Salesforce.

Suppose there is a requirement to fetch all accounts record which don't have any contacts,
how will we do it?

We can fetch account with their corresponding contact record in a in line query.
for example
list<Account> listOfAccounts = [SELECT id, Name,
                                                 (SELECT id,name FROM Contacts)
                                                  FROM Accounts];
list<Account> accountListwithoutContact = new list<Account>();

for(Account act :listOfAccounts ){
      if(act .Contacts !=null && act .Contacts.size() !=0){
              accountListwithoutContact.add(act)   ;
      }

}

accountListwithoutContact list will contain all account which dont have any contacts.

Second approach would be using NOT IN keyword.
list<Account> listOfAccounts = [SELECT id, Name
                                                  FROM Account
                                                  WHERE id NOT IN (SELECT AccountId FROM Contact)];
Now this is the final list which contains all accounts which don't have any contact.

Fetching Unique Record in Salesforce

It seems to be very easy to fetch unique record . You must be thinking Distinct keyword can be used for this. But saleforce does not support Distinct key word.
Another approach is we can us NOT IN key word for this. If we use this some error is there .
list<Account> listofAccounts = [SELECT id, Name 
                          FROM  Account 
                          WHERE Name NOT IN (SELECT Name FROM Account)];

You will face some error;
       COMPILE ERROR: Invalid bind expression type of SOBJECT:Account for column of type String

Because Inner & outer Query should have different object Type. That means if outer query is in Account then inner query must be in Contact.

Then the actual solution is we have to use GROUP BY key word.
GROUP BY returns aggregate result list.
lIST<AggregateResult> listofAccountsAggregateResult = 
                            [SELECT Name
                                                         FROM  Account
                                                         GROUP BY Name];
It will return unique record of Accounts

Monday 21 October 2013

Adding Header Check Box in Pageblock Table

I have faced some requirement in my development work . User must be able to select all the record in the page block table in one click . So I added header check-box  in page block table . 
Here is the code how I achieved this. Only Java Script code I have used .

This is the my page


<apex:page controller="ControllerforheaderCheckboxinPBT">
    <script type="text/javascript">
        
        function checkAll(cb){
            var inputElem = document.getElementsByTagName("input");
            for(var i=0; i<inputElem.length; i++){
                if(inputElem[i].id.indexOf("checkedone")!=-1)
                    inputElem[i].checked = cb.checked;
            }

        } 
     </script>
    
    <apex:pageMessages />
    <apex:form >
       <apex:pageBlock Title="ALL CONTACTS" >
            <apex:commandButton value="mass delete" action="{!massdelete}"  id="massdelete" onclick="return confirmDelete()"/>
            <apex:pageBlockTable value="{!Contacts}" width="100%" var="c" cellpadding="2" border="1"  rowClasses="odd,even" styleClass="tableClass" id="opp_table">
                <apex:column >
                    <apex:facet name="header"> 
                        <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)" rerender="opp_table" status="newStatus"/>
                         </apex:inputCheckbox>
                     </apex:facet>
                    <apex:inputCheckbox value="{!c.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="opp_table"/>
                    </apex:inputCheckbox>
                </apex:column>
                <apex:column headervalue="AccountName" styleClass="showline">
                    <apex:outputField value="{!c.con.AccountId}" />
                </apex:column> 
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

My Controller..


public with sharing class ControllerforheaderCheckboxinPBT {
     public Contact contact{get;set;}
     public Id contactId{get;set;}
     List<ContactWrapper> contactList = new List<ContactWrapper>();
     List<Contact> selectedContacts = new List<Contact>();
     public ControllerforheaderCheckboxinPBT() {
        Contact contact = new Contact();
     }    
    public  List<ContactWrapper> getContacts() {
       for(Contact c: [SELECT Id,Name,Accountid,loginURL__c,Account.Name,MobilePhone,Email FROM Contact ORDER BY createdDate DESC]){
           contactList.add(new ContactWrapper(c));
        }   
       return contactList;
    }
     public PageReference getSelected() {
         System.debug('======Inside the Get Function======');
         selectedContacts.clear();
      
         //adding contacts in list 
         for(ContactWrapper conWrapper: contactList) {
            if(conWrapper.selected == true) {
                conWrapper.isChanged = true;
                selectedContacts.add(conWrapper.con);  
            }                    
          }      
          return null;
      }
      
      public PageReference massDelete() {
          //deleting that list 
 if(selectedContacts.size()>0){
 delete selectedContacts;
 }
              
 //showing an message to select one contact
 else{
 ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select at least one Contact.'));
 return null;
 }
 PageReference headerCheckboxPage = new PageReference('/apex/headerCheckboxinPBT');
 headerCheckboxPage .setRedirect(true);
 return headerCheckboxPage ;
 }
     public class ContactWrapper {
         public Contact con{get; set;}
         public Boolean selected{get; set;}
          
         public ContactWrapper(Contact c) {
            con = c;
            selected = false;
              
         }
      }
    
}

Saturday 19 October 2013

Adding Custom Button Clone In Account

This is a very simple post. We all have seen clone button is present in Standard and Custom Object record except Account. User may expect clone button in Account object also. For them I have done little work around.
When we will create custom button we will find three content source.

  • URL
  • OnCick JavaScript
  • Visulforce page
By using all there we can do clone functionality. But the best choice will be my favorite URL.

Process

  • Go to Customize,  Account ,Buttons, Links, and Actions 
  • Click on New Button or Link
  • Enter Label as Clone
  • Choose Display Type as Detail Page Button
  • Choose Behavior as Display in existing window without header and side bar.
  • Content Source as URL
  • Enter this URL--https://ap1.salesforce.com/{!Account.id}/e?clone=1&retURL=%2F{!Account.Id}
  • Click on Save
  • Now add Clone button in layout.
Let's disccuss something about this URL 
https://ap1.salesforce.com/{!Account.id}/e?clone=1&retURL=%2F{!Account.Id}

Red color text represent your instance name-
e- Edit mode-Record will open in edit mode

Wednesday 16 October 2013

Displaying Image in Pdf

I have come across a scenario image is not appearing in pdf  sometimes.For this I have shared some tricks.
It is very easy to display an image in Visulaforce page.
Process
  • Crate a static resource and store that image
  • Click in View file link 
  • Copy the url
  • Add apex:image tag in vf page.
 <apex:image url = "https://ap1.salesforce.com/resource/logo"  width="180" height="60" />
Image will be displayed. When you render that page as pdf then sometimes image will not be appear.
To appear image every time, I have done some work around and I would love to share it. 

Lets talk about the image url --- "https://ap1.salesforce.com/resource/1380178695000/logo".
All must be familiar with each term except this 1380178695000. What is that value?
This is nothing but the lastmodifiedtime of static resource.1380178695000 must be dynamic. To get dynamic value I have used some function SystemModStamp.

Here is my page and Controller.
<apex:page controller="ImageController" renderAs="pdf" >
  <table>
        <tr>
            <td>
              <div>
                 <apex:image value="{!sLogo}"  width="180" height="60" />
                 <!--<apex:image url="https://ap1.salesforce.com/resource/logo" width="180" height="60" />-->
              </div>
            </td>
        </tr>
    </table>

</apex:page>

Controller is 
public with sharing class ImageController {
    public String sLogo {get;set;}
    public ImageController(){
        list<StaticResource> listOfStaticResources = [SELECT Id,SystemModStamp
                                                      FROM StaticResource
                                                      WHERE Name = 'logo'];
                             
        if(!listOfStaticResources.isEmpty()) {
          sLogo = '/resource/'+listOfStaticResources[0].SystemModStamp.getTime()+'/logo';
       
           System.debug('Printing after slogo'+sLogo );
        } else {
            //sLogo = (invoiceit_s__Configuration__c.getValues('COMPANY_LOGO').invoiceit_s__String_Value__c);
        }
    }
}
Now image will appear in pdf all time.

Thursday 26 September 2013

VisualForce Charting in Salesforce

As salesforce has given us the functionality of report and dashboard to create chart then what is the use of visualforce charting?.
In some situations existing functionality of salesforce can not meet our requirement properly . Suppose there is a requirement to compose custom pages that combine charts and data tables in ways that are more useful to our organization.In that case visual force charting is useful.There are also other way to meet this requirement. We can use Google chart Api for this.In my previous post I have explained.
Visualforce charting gives you an easy way to create customized business charts, based on data sets you create directly from SOQL queries, or by building the data set in your own Apexcode. By combining and configuring individual data series, you can compose charts that display your data in ways meaningful to your organization.
Visualforce charts are rendered client-side using JavaScript. This allows charts to be animated and visually exciting, and chart data can load and reload asynchronously, which can make the page feel more responsive.
This is the my page and controller. 
<apex:page controller="OppsControllernew" tabStyle="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection title="Chart With Table">
                <apex:outputPanel style="float:left;">
                    <apex:chart data="{!Opportunities}" width="500" height="250">
                        <apex:axis type="Numeric" position="left" fields="Amount" title="Amount"/>
                        <apex:axis type="Category" position="bottom" fields="Name" title="Name"/>
                            
                        <apex:barSeries orientation="horizontal" axis="left" xField="Amount" yField="Name"/>
                        <!--<apex:pieSeries dataField="amount" labelField="name"/>-->
                        <apex:legend position="right"/>
                    </apex:chart>
                
                    <apex:chart data="{!Opportunities}" width="500" height="250">
                        <apex:axis type="Category" position="bottom" fields="Name" title="Name" />
                        <apex:axis type="Numeric" position="left" fields="Amount" title="Amount" grid="true"/>
                        <apex:lineSeries axis="left" fill="true"  xField="Name" yField="Amount"  markerType="cross" markerSize="4" markerFill="#FF0000"/>
                  </apex:chart>
                </apex:outputPanel>
              
               <apex:outputPanel style="float:right;margin-right:4cm;height:600px;width:400px;" >
                 <p><b> Opportunity Table</b></p><br/>
                 <apex:pageBlockTable value="{!Opportunities}" var="opp">
                    <apex:column headerValue="Opportunity" value="{!opp.Name}"/>
                    <apex:column headerValue="Amount" value="{!opp.amount}"/>
                    <apex:column headerValue="Created Date" value="{!opp.createddate}" style="width:80px"/>
                </apex:pageBlockTable>
            </apex:outputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
My controller is 

public class OppsControllernew {

    
    // Get a set of Opportunities 
    
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [SELECT Name, Type,createddate, Amount, Closedate FROM Opportunity]));
                setCon.setPageSize(5);
            }
            return setCon;
        }
        set;
    }
    
    public List<Opportunity> getOpportunities() {
         return (List<Opportunity>) setCon.getRecords();
    }

}

Visualforce chart binds to the source of its data through the data attribute on the <apex:chart> component.

Here data source is sObjects that is Opportunity.
Data can be 

  • Name of java script function
  •  Non-Salesforce data sources by building a JavaScript array
  • Apex wrapper objects
The object field names used as data attributes are case-sensitive in JavaScript while field names in Apex and Visualforce are case-insensitive. Be careful to use the precise field name in the fields, xField, and yField attributes of axes and data series components, or your chart will silently fail.Make sure all the name perfectly equal between fields , xFields and yFields.
Limitations Of Visualforce Charting 
  • Visualforce charts only render in browsers which support scalable vector graphics (SVG).
  • Visualforce charts won’t display in pages rendered as PDFs
  • Dynamic (Apex-generated) charting components are not supported at this time
Now the final out put will be like this 

Monday 16 September 2013

Exploring all chart in Visualforce page by using JavaScript Remoting & Google Charts API.

This post is all about how to draw a chart in Visual force page by using JavaScript Remoting & Google Charts API.
I had faced some requirement to draw a different types of chart in a visualforce page and also to display number of  distinct record for further reference. I had done some work around and finally I had reached to the final destination. Here I have created one object ChartObject__c and two field Name and Amount.
Here I am sharing some code snippet for your reference. 

<apex:page controller="GoogleChartsController" sidebar="false">

    <!-- Google API inclusion -->
    <apex:includeScript id="a" value="https://www.google.com/jsapi" />
    <apex:sectionHeader title="Google Charts + Javascript Remoting" subtitle="Demoing - Opportunities by Exepected Revenue"/> 
    
    <!-- Google Charts will be drawn in this DIV -->
    <div id="chartBlock"/>
    <div id="chartBlockpie"/>
    <div id="chartBlockline"/>
    <div id="chartBlockbar" />
    <div id="chartBlockgauge" />
     
    <script type="text/javascript">
     
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initCharts);

function initCharts() {   
  
// Following the usual Remoting syntax
// [<namespace>.]<controller>.<method>([params...,] 
//<callbackFunction>(result, event) {...}
// namespace : 
// controller : GoogleChartsController
// method : loadOpps
 
GoogleChartsController.loadOpps(
function(result, event){ 
 
// load Column chart
var visualization = new google.visualization.ColumnChart(document.getElementById('chartBlock'));

// Prepare table model for chart with columns
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Amount');  
 
// add rows from the remoting results
for(var i =0; i<result.length;i++){
var r = result[i];
data.addRow([r.Name, r.Amount__c]);
}
var chart = new google.visualization.PieChart(document.getElementById('chartBlockpie'));
chart.draw(data, result);
 
var chart = new google.visualization.LineChart(document.getElementById('chartBlockline'));
chart.draw(data, result);
 
var chart = new google.visualization.BarChart(document.getElementById('chartBlockbar'));
chart.draw(data, result);
 
/*var chart = new google.visualization.ScatterChart(document.getElementById('chartBlockscater'));
chart.draw(data, result);*/
 
var chart = new google.visualization.GaugeChart(document.getElementById('chartBlockgauge'));
chart.draw(data, result);
 
// all done, lets draw the chart with some options to make it look nice.
visualization.draw(data, {legend : {position: 'top', textStyle: {color: 'blue', fontSize: 10}}, width:window.innerWidth,vAxis:
{textStyle:{fontSize: 10}},hAxis:{textStyle:{fontSize: 10},showTextEvery:1,slantedText:false}});


  },{escape:true});
 }
       </script>
    <p>Total Different Kind Of Production:<apex:outputText value="{!totalvalue}"/></p>
</apex:page>

My controller

global with sharing class GoogleChartsController {
public Integer totalvalue{get;set;}
    public GoogleChartsController() {
   
// Integer totalvalue;
list<AggregateResult>  Namecount=new List<AggregateResult>();
Namecount= [select  COUNT_DISTINCT(Amount__c) ctr from ChartObject__c];
        for(AggregateResult sobj:Namecount){
          
totalvalue=Integer.valueOf(sobj.get('ctr'));
        }
        System.debug('################asish####################'+totalvalue);
   } 
    
    /**
      Loads most recent 10 Opportunities
    */
    @RemoteAction   
    global static ChartObject__c[] loadOpps() {
       
        return  [select Id, Name, Amount__c from ChartObject__c  order by CreatedDate DESC limit 10];
       
    }  
}
Here I am sharing some image regarding chart.


Wednesday 11 September 2013

Uses Of Apex Repeat


An iteration component that allows you to display the contents of a collection according to a structure that you specify. The collection can include up to 1,000 items.

This component cannot be used as a direct child of the following components:
<apex:dataTable>
<apex:pageBlockTable>
<apex:panelBar>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectRadio>
<apex:tabPanel>

Suposse there is a requirement, you need to display Five accounts with thier Contacts in a visualforce page.Format should be like this image


How will you do it?
It is very simple, just use repeat in visualforce page.
Here is visualforce page and controller

<apex:page controller="UseofRepeatOnAccountController" sidebar="false" tabStyle="Account">
    <apex:form >
    <apex:pageBlock title="Accounts with assoicated Contacts">
        <apex:repeat value="{!accountList }" var="acc">
            <apex:pageBlockSection title="{!acc.name}">
                <apex:pageBlockTable value="{!acc.contacts}" var="con">
                    <apex:column value="{!con.Firstname}"/>
                    <apex:column value="{!con.Lastname}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:repeat>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Controller is..
public class UseofRepeatOnAccountController {
    public List<Account> accountList{get;set;}
   
    public UseofRepeatOnAccountController() {
        accountList = new List<Account>();
        accountList = [SELECT id, Name,(SELECT LastName ,FirstName From Contacts)From Account limit 5] ;
    }
}

Thursday 22 August 2013

Generating pdf Using Conga Composer

Conga Composer lets you to create documents from a button or link placed on a Salesforce.com page layout. It merges Salesforce.com data with Word, Excel, PowerPoint, email, or PDF templates to create finished documents.

Benefit Of Conga Composer

  • Easily create and deliver customized documents, 
  • Presentations and reports using Word, PowerPoint, Excel, HTML email and PDF forms from standard & custom objects. 
  • Generate quotes, proposals, account plans, invoices, contracts, letters & more.
In order to use Conga Composer, we need to install two things.
  •     Conga Composer 
  •     Conga Query Manager.

If we need to use some related object's record then Conga Query Manager is necessary otherwise Conga Composer is enough.

How to Install Conga Composer


Go through this link for installation .

http://knowledge.appextremes.com/appextremes/ext/kb110-how-to-install-conga-composer

How to Install Conga Query Manager


Go through this link for installation .

http://knowledge.appextremes.com/appextremes/ext/kb611-how-to-install-conga-query-manager

We already have some sample design in our local drive which signifies how the information will be presented , If we don't have then we will make one using word or anything else.

Now we will create  Conga Template and Conga Query.



Creating Conga Template

Click New button on Conga Template to create one template
After template creation ,click on AttachFile button to attach some sample template from your local drive.






Creating Conga Query

If we have to display some related object record then we have to create conga query to pull data from salesforce, here we can define as many query as want.
There is field called SOQL Select Statement where we have to write query.
For example query will be like this 

SELECT invoiceit_s__Accounting_Code__c, invoiceit_s__Charge_Date__c, invoiceit_s__Service_End_Date__c, invoiceit_s__Service_Start_Date__c, CreatedById   FROM invoiceit_s__Invoice_Lines__c WHERE invoiceit_s__Invoice__c = '{pv0}

Here we are querying data from invoice lines that means button must be in invoice page.

There are two different approach for generating document.

  • By Clicking a Button
  • Some Automation process by using Work flow  

By Clicking a Button
  • Create a custom button on master object 
  • Choose content source as URL
  • paste this code 

https://www.appextremes.com/apps/Conga/PointMerge.aspx?SessionId={!API.Session_ID}
   &ServerUrl={!API.Partner_Server_URL_80}
   &Id={!Credit_Note__c.Id} //object id where button is present
   &DefaultPDF=1
   &PartnerCode=0015000000Yd8nM // optionals 
  &EmailReplyToId{!User.Id}
  &EmailToId={!Credit_Note__c.Billing_ContactId__c}//to whom emil is going
  &EmailRelatedToId={!Credit_Note__c.Id}//object id where button is present
  &TemplateId=a0mb0000000KYO0 // conga templae id which you have created
  &QueryID=[CreditLines]a0nb0000000zgUE //conga query id, you can give many query id by using comma

How to use Conga Composer 

Go through this pdf 

Automation Process
  • Create one formula field and one checkbox field on mater object.
  • When that check box is true then workflow will be fired.
  • Create a email template through which email will be going to the customer.
  • In the formula field paste this code 

 "&Id="+Id 
   +"&TemplateId=a0pW000000335Xt" //conga template id
   +"&EmailTemplateId=00XW0000000M8Hp" //the emailtemplate id which you have created
   +"&QMode=3" 
   +"&DefaultPDF=1" 
   + "&EmailToId=" + invoiceit_s__Billing_Contact__c 
   +"&QueryID=a11W0000000ov1y,a11W0000000ov1t" //conga query id
   +"&EmailRelatedToId="+Id

  • Create work flow and an outbound message.
  • Give End point Url as https://workflow.appextremes.com/apps/Conga/PMWorkflow.aspx.
  • Select that formula field Account fields to send to selected fields.
  • Click on Save
Now work flow and outbound message is ready, when that checkbox will be ready a mail with attachment will reach to the contact's email.
For more information about salesforce conga work flow , please go through this pdf