I have apex code that dynamically creates SObject records based on configurations (metadata type records). The code needs to evaluate on-the-fly, if the Sobject field that should be "put" (sObjectRecord.put(fieldName, fieldValue
) is from a read-only system field or a regular, writable field.
The code will run in system context, so this is not about permissions but about database enforced read-only fields.
Typical fields that should be recognized as read-only are:
- CreatedDate, LastModifiedDate, etc
- CreatedById, LastModifiedById, etc
- All auto-number fields (custom and standard, such as Order.OrderNumber)
- All formula fields
- The standard id fields (
Id
)
My current code works like this:
public Boolean isWriteable() {
// always return false for formula and autonumber fields
if (fieldDescribe.isCalculated()) return false;
if (fieldDescribe.isAutoNumber()) return false;
// get all read-only system fields: they are not permissionable, accessible but not update/writable for current user
if (!fieldDescribe.isPermissionable() && fieldDescribe.isAccessible() && !fieldDescribe.isCreateable() && !fieldDescribe.isUpdateable()) return false;
// always return false for compound fields and other fields that are not intended to be written
switch on fieldDescribe.getType() {
when address { return false; }
when base64 { return false; }
}
return true;
}
So far, the debug logs show me satisfying results. Anything I forgot? Please help me to improve the code.