Sunday, 29 June 2014

Lead Conversion in Apex

Here i am going to explain how to convert lead using apex code.
We have "ConvertLead()" method in apex to convert lead.To use this we just need to insert lead first after that we need to pass lead id into "setLeadId()" method as shown below.
Lead leadobj=new Lead();
leadobj.Company = 'AbC Company;
leadobj.LastName = 'Balaji';
insert leadobj;
//Passing lead id
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadobj.id);
//Getting converted status of lead from LeadStatus
//This is used to get Converted Status we set on lead with Lead Status field.
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
//setting convert status.
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr=Database.convertLead(lc);

After converting lead we can get ConvertedAccountId,ConvertedContactId,ConvertedOpportunityId.

Some times we don't want to create Account ,Contact from lead Conversion. Because those may be existing  with the same names. Then we can set existing AccountId, Contactid in lead conversion as shown in below.

Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadobj.id);  
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr=Database.convertLead(lc);
 lc.setLeadId(leadobj.id);
 lc.setAccountId(existingaccountId);  
 lc.setContactId(existingContactId);

If we do conversion with this method then we can have all the standard functionalities as in standard lead conversion.




Quote Sync in Apex

Here i am going to explain how to sync quote in apex .

We have "SyncedQuoteId" field on Opportunity object. If we want to sync a quote with opportunity then we just need to update opportunity with Quote Id as shown below. Then the Quote will be in sync with opportunity which we updated.


Opportunity oppobj=new Opportunity(id=opportunityId,SyncedQuoteId=quoteobj.id);
 update oppobj;

Record Type Id without SOQL query

Hi,

We have getRecordTypeInfosByName() method to get record type id with out SOQL query.
We can avoid SOQL query on RecordType object with this method.The following example shows how to access Record Type information through dynamic apex.

Schema.DescribeSObjectResult resSchema = Account.sObjectType.getDescribe();
//getting all Recordtype  Account
Map<String,Schema.RecordTypeInfo> recordTypeInfo = resSchema.getRecordTypeInfosByName(); 
//Getting Business Record Type Id
Id rtId = recordTypeInfo.get('Business').getRecordTypeId();