I have created custom convert button on custom object which is to create account, contact & opportunity.Here i have attached the Apex code and visual force page code. After I click "convert" I am getting this error.
Error Message:
**SObject row was retrieved via SOQL without querying the requested field: CustomLead_c.CompanyName_c
Error is in expression '{!convertlead}' in component in page leadconversion
An unexpected error has occurred. Your development organization has been notified.**
Apex code:
public class LeadConversion {
public PageReference RedirecttoLead()
{
String currentLead = '/' + leadObj.Id;
PageReference pageRef = new PageReference(currentLead);
return pageRef;
}
private CustomLead__c leadObj;
// The extension constructor initializes the private member
// variable acct by using the getRecord method from the standard
// controller.
public LeadConversion(ApexPages.StandardController stdController)
{
System.debug('******Sai******');
leadObj = (CustomLead__c)stdController.getRecord();
}
public void convertLead(){
Account acc = new Account();
acc.Companynamelead__c = leadObj.CompanyName__c;
//acc.BillingAddress = leadObj.Address;
try
{
insert acc;
}
Catch (Exception ex1)
{
ex1.getmessage();
}
Contact cc = new Contact();
cc.Lastname_lead__c = leadObj.LastName_c__c;
//cc.BillingAddress = leadObj.Address;
try
{
insert cc;
}
Catch (Exception ex2)
{
ex2.getmessage();
}
Opportunity opp = new Opportunity();
opp.opp_namelead__c = leadObj.opp_name__c;
//opp.BillingAddress = leadObj.Address;
try
{
insert opp;
}
Catch (Exception ex3)
{
ex3.getmessage();
}
}
}
Visual force code:
<apex:page standardController="CustomLead__c" cache="true" action="{!convertlead}" extensions="LeadConversion" >
<br/><br/>
<apex:messages style="color:red; font-weight:bold; text-align:center;"/>
<apex:form >
<center>
<apex:commandLink value="Redirect to Lead" style="color:blue; font-weight:bold;" action="{!RedirecttoLead}"/>
</center>
</apex:form>
</apex:page>
Best Answer
Generally what this means is that your controller is trying to reference a field that has not been populated. By default, Visualforce controllers will retrieve values for all fields referenced in the Visualforce page and no others. You can solve this in one of two ways:
Add the field to your VF page with an output field that has
rendered="false"
:My preference is to use the outputText field for the following reasons:
Update
As Andrew mentioned in the comments, there is a third option: use the addFields() method on the StandardController. This might be the cleanest option since it does not add clutter to your VF page.