function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
msb-appsupport1.3905906418879758E12msb-appsupport1.3905906418879758E12 

How could I create a new lead setting a required recordType using code?

I want to use Apex code and visualforce page to create a new lead.

In web, I need to choose a record type before I create a new lead. And there are three types of leads.
In visualforce page, I want to create a new lead with assigned record type using code.

The confusion for me is that the recordType is related list for the lead. I could extract a list of record type by the following.

for (list<RecordType> rts : [SELECT ID, name FROM RecordType WHERE SObjectType = 'Lead' Order by name])

However, I could not pull out the recordType for a lead by the following, since the recordType is related list.

Lead l = [SELECT RecordType FROM LEAD].

Besides, what I want is create a new lead like below.
Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordType = 'registration type lead');

Could anyone help me with this to access the related list using apex code or visualforce page?

Thanks a lot.
Best Answer chosen by msb-appsupport1.3905906418879758E12
Ramu_SFDCRamu_SFDC
So basically record types are lookup fields that refer to record type object. We cannot pull the record type name directly by querying as SELECT RecordType FROM LEAD instead you need to get the id's of record types as SELECT RecordTypeid FROM LEAD.

In the last line of code you need to change the recordtype field to recordtypeid field and instead of name give the id something as below

Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordTypeid = '<id of record type>');

All Answers

Ramu_SFDCRamu_SFDC
So basically record types are lookup fields that refer to record type object. We cannot pull the record type name directly by querying as SELECT RecordType FROM LEAD instead you need to get the id's of record types as SELECT RecordTypeid FROM LEAD.

In the last line of code you need to change the recordtype field to recordtypeid field and instead of name give the id something as below

Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordTypeid = '<id of record type>');
This was selected as the best answer
MagulanDuraipandianMagulanDuraipandian
http://www.infallibletechie.com/2014/03/how-to-get-recordtypeid-using-record.html
This helps to avoid SOQL.

If this solves your problem, kindly mark it as the best answer.

Regards,
Magulan
http://www.infallibletechie.com