Feels like I'm not having a good day at all with platform :-) ... another day and another issue with platform dynamic sObjects :(
So I'm trying to create an sObject record dynamically from a VF page. In that there is a Lookup field to be included in the form dynamically. Now, usually lookup field value can be selected by using the lookup button to search and select a specific record OR by simply typing the name of the record. Platform selects a valid record or alert user that record entered by name do not exist or not found.
So now I'm seeing with dynamic sObjects it is thrown an untrappable error:
SObject row does not allow errors
To test it, simply copy my code below and in the Account Lookup field enter a value 12345xyz
(or simply a value that you're sure do not exist in your org as an Account
).
And press Save
button, you get this error, and everything on the form is lost even if you have placed try/catch
in your code.
VF Page:
<apex:page controller="MyTestDynamicSObject">
<apex:form id="theForm">
<apex:pageBlock mode="edit">
<apex:pageMessages />
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{!saveRecord}" value="Save" reRender="theForm" status="loading" />
<apex:actionStatus id="status" startText="(loading...)"></apex:actionStatus>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1">
<apex:inputField value="{!sObjRecord['LastName']}" required="false" /><br />
<apex:inputField value="{!sObjRecord['AccountId']}" required="false" /><br /><br />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
APEX Class:
public class MyTestDynamicSObject {
public MyTestDynamicSObject() {
sObjRecord = (sObject) Schema.getGlobalDescribe().get('Contact').newSObject(null, true);
sObjRecord.put('LastName', 'Test name');
}
public sObject sObjRecord { get;set; }
public void saveRecord() {
try {
insert sObjRecord;
} catch (Exception ex) {
ApexPages.addMessages(ex);
}
}
}
sample
reproducible code. My code is lot complex than this, it has to supportany
sObject
in the org and form is generated dynamically with dynamic number of fields.